I have the following test code using NSubstitute:
[TestMethod]
public void Test()
{
var foo = Substitute.For<IFoo>();
foo.Foo(Arg.Is<Bar>(b => !b.X)).Returns(0); // Line 1
foo.Foo(Arg.Is<Bar>(b => b.X)).Returns(1); // Line 2
}
public interface IFoo
{
int Foo(Bar b);
}
public class Bar
{
public bool X;
}
When line 2 is executed, an exception is thrown:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
However, the exception is not thrown if I change !bX
to b != null && !bX
. It seems that the lambda expression in line 1 is being evaluated with a null lambda variable when line 2 is called.
My intention is to have more than one call configuration for the method I'm mocking. So, am I doing this wrong? Is there another way to do this?
The problem is that the last setup on a mocked member overrides any previous arrangements.
The desired behavior can be achieved with
//Arrange
var foo = Substitute.For<IFoo>();
foo.Foo(Arg.Any<Bar>()).Returns(args => args.Arg<Bar>().X ? 1 : 0);
//...
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.