Mocking a return type from another Mocked type using Moq
c#, mocking, moq
Solution
Something like this should work:
var mockFooRepository = new Mock<IFooRepository>();
mockFooRepository.Setup(r => r.Add(It.IsAny<IBar>()))
.Returns<IBar>(bar =>
{
var item = new Mock<IFooItem>();
item.Setup(i => i.fooItemId)
.Returns(bar.Id);
return item.Object;
});
This assumes that `IBar` looks like this:
public interface IBar
{
int Id { get; set; }
}
Problem
So I'm trying to return a mocked type from another Mocked type, I've made some progress but I'm stuck here (interface names have been simplified) Consider the interface IFoo and IFooItem. Calling Add on an IFoo type, passing in an IBar returns an IFooItem ``` interface IFoo { IFooItem Add(IBar bar); } interface IFooItem { int fooItemId {get; set;} } ``` Also I have a IFooRepository, which I'm trying to use Moq to mock so I can mock adding an item. So, ``` var mockFooRepository = new Mock<IFooRepository>(); mockFooRepository.Setup(m=> m.Add(It.IsAny<IBar>())) .Returns( // What is the correct way to mock properties of a new IFooItem from // mocked properties of IBar // essentially a new mocked type of IFooItem that can read from IBar // so IFooItem.Property = somevalue, IFooItem.Property2 = IBar.SomeProp ); ```