如何回归Moq方法"这个"

时间:2016-10-18 18:43:01

标签: c# unit-testing moq

我有一个界面

interface IService
{
    IService Configure();
    bool Run();
}

"真实"实现这样做:

class RealService : IService
{
    public IService Configure()
    {
        return this;
    }

    public bool Run()
    {
        return true;
    }
}

使用Moq模拟服务会创建一个返回Configure()的{​​{1}}默认实现。

有没有办法在Moq中设置返回模拟实例的方法?

3 个答案:

答案 0 :(得分:4)

假设您使用的是Moq,您可以简单地Setup模拟返回自己:

var mock = new Mock<IService>();

mock.Setup(service => service.Configure()).Returns(mock.Object);

var testClass = new TestClass(mock.Object);

然后验证方法是否返回了您期望的内容:

Assert.AreEqual(mock.Object, testClass.DoStuff());

答案 1 :(得分:2)

您可以创建另一个使用相同界面的Mock对象并将其返回:

[TestClass]
public class UnitTest1
{

    [TestMethod]
    public void TestMethod1()
    {
        var serviceMock1 = new Mock<IService>();
        var serviceMock2 = new Mock<IService>();

        serviceMock1.Setup(service => service.Configure())
            .Returns(serviceMock2.Object);

        var testClass = new TestClass(serviceMock1.Object);

        Assert.IsNotNull(testClass.DoStuff());
    }
}

public class TestClass
{
    private readonly IService _service;

    public TestClass(IService service)
    {
        _service = service;
    }

    public IService DoStuff()
    {
        return _service.Configure();
    }
}


public interface IService
{
    IService Configure();
    bool Run();
}

public class RealService : IService
{
    public IService Configure()
    {
        return this;
    }

    public bool Run()
    {
        return true;
    }
}

答案 2 :(得分:2)

无论哪种方式都可以设置返回模拟实例的方法。

//Arrange
var instance = Mock.Of<IService>();//mocked instance
var mockService = Mock.Get(instance);//mock object used to setup instance functionality
//setup method to return mocked instance
mockService.Setup(m => m.Configure()).Returns(instance);

或者

//Arrange
var mockService = new Mock<IService>();//mock object used to setup instance functionality
var instance = mockService.Object;//mocked instance
//setup method to return mocked instance
mockService.Setup(m => m.Configure()).Returns(instance);