问题
I'm not sure how I would do this.
Given I have
public interface IFactory<T> where T : new()
{
IWrapper<T> GetT(string s);
}
public interface IWrapper<out T> where T : new()
{
void Execute(Action<T> action);
}
When I do this
public class MoqTest
{
public void test()
{
Mock<IWrapper<basicClass>> wrapperMock = new Mock<IWrapper<basicClass>>();
Mock<IFactory<basicClass>> factoryMock = new Mock<IFactory<basicClass>>()
.Setup(p => p.GetT(It.IsAny<string>()))
.Returns(wrapperMock.Object);
}
}
I get this
Cannot implicitly convert type
Moq.Language.Flow.IReturnsResult<TestNamespace.IFactory<TestNamespace.basicClass>>
toMoq.Mock<TestNamespace.IFactory<TestNamespace.basicClass>>
. An explicit conversion exists (are you missing a cast?)
Note that these are just mocked example objects.
It seems it doesn't consider the return type equivalent. One being a IReturnResult
, the other a Moq.Mock
回答1:
Your problem basically is that you are assigning the result of invoking the Returns
method to the factoryMock
variable.
You want to first create the mock and assign it to the factoryMock
variable and then set the mock up like this:
Mock<IWrapper<basicClass>> wrapperMock = new Mock<IWrapper<basicClass>>();
Mock<IFactory<basicClass>> factoryMock = new Mock<IFactory<basicClass>>();
factoryMock
.Setup(p => p.GetT(It.IsAny<string>()))
.Returns(wrapperMock.Object);
来源:https://stackoverflow.com/questions/38244204/return-a-mock-from-a-mocked-method