C# 验证是否使用NSSubstitute抛出异常调用了异步方法
当我尝试使用C# 验证是否使用NSSubstitute抛出异常调用了异步方法,c#,.net,nsubstitute,C#,.net,Nsubstitute,当我尝试使用NSubstitute验证是否调用了异步方法时,会收到一条错误消息 nssubstitute扩展方法(如.Received())只能对使用Substitute.For()和相关方法创建的对象调用 下面是一些示例代码来说明我的观点: public interface ISender { Task Send(string message); } public class Service { private readon
NSubstitute
验证是否调用了异步方法时,会收到一条错误消息
nssubstitute扩展方法(如.Received())只能对使用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);
}
公共接口ISender
{
任务发送(字符串消息);
}
公务舱服务
{
专用只读ISender\u发送方;
公共服务(ISender发送者)
{
_发送方=发送方;
}
公共异步任务SendMessage(列出消息)
{
foreach(消息中的var消息)
{
等待发送者。发送(消息);
}
}
}
[测试]
公共异步任务测试异步方法()
{
var mock=replacement.For();
var服务=新服务(模拟);
var messages=新列表{“Foo”,“Bar”};
等待服务。发送消息(消息);
mock.Send(Arg.Any()).Received(2);
}
我知道问题在于我正在验证
任务
,而不是mock.Send(Arg.Any())
,但是我能做些什么呢 您应该反转调用:
mock.Received(2).Send(Arg.Any());
来源:您应该反转调用:
mock.Received(2).Send(Arg.Any());
来源:正在工作!谢谢工作谢谢