When checking received calls on an interface I can do this:
void Main()
{
var logger = Substitute.For<ILogger>();
Test(logger);
logger.Received().Log(Arg.Any<string>());
}
public void Test(ILogger logger)
{
logger.Log("Test");
}
public interface ILogger
{
void Log(string message);
}
If I comment out the logger.Log("Test");
call I get this:
ReceivedCallsException: Expected to receive a call matching:
Log(any String)
Actually received no matching calls.
However, I just recently discovered that NSubstitute can substitute for delegates. The question is, can I get it to check if the delegate was called?
void Main()
{
var logger = Substitute.For<Action<string>>();
Test(logger);
// What.Received().What()?
}
public void Test(Action<string> logger)
{
logger("Test");
}
The answer to this was actually quite simple.
I'm not substituting a "function call", I'm of course substituting the whole delegate type, not just the call syntax part.
So this works just fine:
logger.Received()(Arg.Any<string>());
Produces (provided I comment out the call to the delegate):
ReceivedCallsException: Expected to receive a call matching:
Invoke(any String)
Actually received no matching calls.
Depending on your opinions on the syntax it can be made "clearer" by just spelling out what is happening:
logger.Received().Invoke(Arg.Any<string>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With