简体   繁体   中英

Verify that an async method was called using NSubstitute throws exception

When I try to verify that an async method was called using NSubstitute , I get an error message

NSubstitute extension methods like .Received() can only be called on objects created using Substitute.For() and related methods

Here's some example code to illustrate my point:

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

I understand that the problem is that I'm verifying Task and not mock.Send(Arg.Any<string>()) , but what can I do about it?

You should invert the calls:

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

Source: http://nsubstitute.github.io/help/received-calls/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM