如何通过 NSubstitute 监视方法 return 的值

How to spy method return value by NSubstitute

我想监视 return NSubstitute 中模拟接口的模拟方法的值。我得到 Received 函数的 return 值,但它总是 returns null

public interface IFactory
{
    object Create();
}

public interface IMockable
{
    object SomeMethod();
}

public class Mockable : IMockable
{
    private readonly IFactory factory;

    public Mockable(IFactory factory)
    {
        this.factory = factory;
    }

    public object SomeMethod()
    {
        object newObject = factory.Create();
        return newObject;
    }
}

public class TestClass
{
    [Fact]
    void TestMethod()
    {
        var factory = Substitute.For<IFactory>();
        factory.Create().Returns(x => new object());
        IMockable mockable = new Mockable(factory);
        object mockableResult = mockable.SomeMethod();
        object factoryResult = factory.Received(1).Create();
        Assert.Equal(mockableResult, factoryResult);
    }
}

我希望 mockableResultfactoryResult 相等,但 factoryResultnull

那是你用错了。 Received 是对被调用方法的断言。它不是 return 模拟成员的可用值。

查看您的测试的后续修改版本,其行为符合您的预期。

public class TestClass {
    [Fact]
    void TestMethod() {
        //Arrange
        object factoryResult = new object(); //The expected result
        var factory = Substitute.For<IFactory>();
        factory.Create().Returns(x => factoryResult); //mocked factory should return this
        IMockable mockable = new Mockable(factory);

        //Act
        object mockableResult = mockable.SomeMethod(); //Invoke subject under test

        //Assert
        factory.Received(1).Create(); //assert expected behavior
        Assert.Equal(mockableResult, factoryResult); //objects should match
    }
}