如何通过NSubstitute监视方法返回值

时间:2019-06-09 11:36:06

标签: c# unit-testing nsubstitute spy

我想监视NSubstitute中模拟接口的模拟方法的返回值。我得到Received函数的返回值,但它总是返回 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相等,但是factoryResult null

1 个答案:

答案 0 :(得分:2)

那是因为您使用不正确。 Received是对被调用方法的断言。它不会从模拟成员中返回可用的值。

查看测试的以下修改版本,其行为与您预期的一样。

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