我想监视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);
}
}
我希望mockableResult
和factoryResult
相等,但是factoryResult
为 null 。
答案 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
}
}