[英]How to spy method return value by NSubstitute
I want to spy return value of a mocked method of a mocked interface in NSubstitute. 我想在NSubstitute中监视模拟接口的模拟方法的返回值。 I get return value of Received
function but it always returns null . 我得到了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);
}
}
I expect that mockableResult
and factoryResult
be equal but factoryResult
is null . 我希望mockableResult
和factoryResult
相等,但是factoryResult
为null 。
That is because you are using it incorrectly. 那是因为您使用不正确。 Received
is an assertion on the called method. Received
是关于被调用方法的断言。 It does not return a usable value from mocked members. 它不会从模拟成员中返回可用值。
Review the follow modified version of your test that behaves as you would have expected. 查看行为符合预期的测试的以下修改版本。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.