When using NSubstitute, to make it possible to do things like substitute.Foo().Returns(7)
, calling Foo()
on a substitute sets some internal state that says "Next time Returns()
is called, I'm the method you're setting the return value on". This means that if you call anything on any substitute inside a call to Returns()
you'll end up in a mess.
I've ran into problems with this when doing stuff like:
substitute.Foo().Returns(CreateSomethingThatUsesNSubstitute())
This kind of problem can take a while to track down. To fix it, you need to assign the result of CreateSomethingThatUsesNSubstitute()
to a local first. e.g.
var theResult = CreateSomethingThatUsesNSubstitute();
thing.Foo().Returns(theResult)
Once you've done that, everything should work as expected.