Return a Mock from a Mocked method

跟風遠走 提交于 2019-12-11 04:13:14

问题


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>> to Moq.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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!