如何Moq返回“this”的方法

本文关键字:方法 this Moq 返回 如何 | 更新日期: 2023-09-27 18:13:31

我有一个接口

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

"真正的"实现是这样做的:

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

使用Moq模拟服务创建一个默认的Configure()实现,返回null

是否有一种方法来设置方法在Moq返回模拟实例?

如何Moq返回“this”的方法

假设您正在使用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());

这两种方法都可以设置返回模拟实例的方法。

//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);

您可以创建另一个使用相同接口的Mock Object并返回它:

[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;
    }
}