验证使用NSubstitute调用异步方法抛出异常

时间:2017-03-24 12:17:34

标签: c# .net nsubstitute

当我尝试验证使用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>()),但我该怎么办呢?

1 个答案:

答案 0 :(得分:3)

你应该反转这些电话:

mock.Received(2).Send(Arg.Any<string>());

来源:http://nsubstitute.github.io/help/received-calls/