gpt4 book ai didi

c# - N用代表代替,检查收到的电话?

转载 作者:太空狗 更新时间:2023-10-30 00:48:06 34 4
gpt4 key购买 nike

在接口(interface)上检查接收到的调用时,我可以这样做:

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);
}

如果我注释掉 logger.Log("Test"); 调用,我会得到:

ReceivedCallsException: Expected to receive a call matching:
Log(any String)
Actually received no matching calls.

然而,我最近才发现 NSubstitute 可以替代委托(delegate)。问题是,我能否让它检查委托(delegate)是否被调用?

void Main()
{
var logger = Substitute.For<Action<string>>();
Test(logger);
// What.Received().What()?
}

public void Test(Action<string> logger)
{
logger("Test");
}

最佳答案

这个问题的答案其实很简单。

我不是在替换“函数调用”,我当然是在替换整个委托(delegate) type,而不仅仅是调用语法部分。

所以这很好用:

logger.Received()(Arg.Any<string>());

产生(假设我注释掉了对委托(delegate)的调用):

ReceivedCallsException: Expected to receive a call matching:
Invoke(any String)
Actually received no matching calls.

根据您对语法的看法,只需拼出正在发生的事情,它就可以变得“更清晰”:

logger.Received().Invoke(Arg.Any<string>());

关于c# - N用代表代替,检查收到的电话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49815683/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com