I want to spy return value of a mocked method of a mocked interface in NSubstitute. I get return value of Received
function but it always 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);
}
}
I expect that mockableResult
and factoryResult
be equal but factoryResult
is null .
That is because you are using it incorrectly. Received
is an assertion on the called method. 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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.