当我尝试验证使用NSubstitute
调用异步方法时,收到错误消息
像.Received()这样的NSubstitute扩展方法只能在使用Substitute.For()和相关方法创建的对象上调用
以下是一些示例代码来说明我的观点:
public interface ISender
{
Task Send(string message);
}
public class Service
{
private readonly ISender _sender;
public Service(ISender sender)
{
_sender = sender;
}
public async Task SendMessage(List<string> messages)
{
foreach (var message in messages)
{
await _sender.Send(message);
}
}
}
[Test]
public async Task Test_Async_Method()
{
var mock = Substitute.For<ISender>();
var service = new Service(mock);
var messages = new List<string>{"Foo","Bar"};
await service.SendMessage(messages);
mock.Send(Arg.Any<string>()).Received(2);
}
我理解问题在于我正在验证Task
而不是mock.Send(Arg.Any<string>())
,但我该怎么办呢?
答案 0 :(得分:3)
你应该反转这些电话:
mock.Received(2).Send(Arg.Any<string>());