Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute with delegates, checking received calls?

Tags:

c#

nsubstitute

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");
}
like image 929
Lasse V. Karlsen Avatar asked Apr 13 '18 11:04

Lasse V. Karlsen


1 Answers

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>());
like image 167
Lasse V. Karlsen Avatar answered Sep 27 '22 21:09

Lasse V. Karlsen