NSubstitute with delegates, checking received calls?

ang*_*son 4 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);
}
Run Code Online (Sandbox Code Playgroud)

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");
}
Run Code Online (Sandbox Code Playgroud)

ang*_*son 6

答案实际上很简单。

我不是在替换“函数调用”,而是在替换整个委托类型,而不仅仅是调用语法部分。

所以这很好用:

logger.Received()(Arg.Any<string>());
Run Code Online (Sandbox Code Playgroud)

产生(前提是我将对呼叫的调用注释掉):

ReceivedCallsException:预期接收匹配的呼叫:
Invoke(任何String)
实际未收到匹配的呼叫。

根据您对语法的看法,只需说明正在发生的事情,就可以使它“更清晰”:

logger.Received().Invoke(Arg.Any<string>());
Run Code Online (Sandbox Code Playgroud)