How can I check if an anonymous function has been called in NSubstitute?
I want to check if an anonymous function was called with NSubstitute. The method in the class I take in a parameter Func<>
and I want to make sure that the parameter is being called (or not called). I've tried the following but it doesn't work:
var spy = Substitute.For<Func<string, int>>();
MyClass.DoSomething(spy);
spy.Invoke(Arg.Any<string>()).Received();
This throws an exception:
NSubstitute.Exceptions.NullSubstituteReferenceException : NSubstitute extension methods like .Received can only be called on objects created using Substitute.For<T>() and related methods.
source to share
Try to replace
spy.Invoke(Arg.Any<string>()).Received();
from
spy.Received().Invoke(Arg.Any<string>());
It makes no difference if your production code calls func through spy.Invoke()
or through spy()
. But the test will fail if your code calls BeginInvoke
. But I think this shouldn't be a problem, because you should know in advance if a test is required for Invoke
or BeginInvoke
.
source to share