9

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");
}
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825

1 Answers1

10

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>());
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825