简体   繁体   中英

Mocking external responses with NSubstitute

I have a method that calls various services and uses their output later. Something like this:

myOutput1 = await _apiCaller.Call(() => _myService.someCall(someData));
myOutput2 = await _apiCaller.Call(() => _myService.anotherCall(otherData));

I would like to just mock the responses to these with NSubstitute, without waiting for the calls.

However, it doesn't look like NSubstitute catches the internal function call (eg someCall , anotherCall ), so I have to mock the API caller. This is a problem in two ways: I can't seem to differentiate between the two function inputs, and more broadly, even properly mock the caller.

I am doing the following:

sub._apiCaller.Call(default).ReturnsForAnyArgs(Task.FromResult(myMockData));

But still get a null result in myOutput# .

What is the correct way to mock the results of such calls, and is there a way to differentiate the internal function call?

This is somewhat similar to what you are suggesting. The idea will be the same in terms of how you go about mocking the internal service.

[TestClass]
    public class UnitTest1
    {
        private IMyService _myService;
        private ApiCaller _apiCaller;

        [TestInitialize]
        public void Initialize()
        {
            _apiCaller = new ApiCaller();
            _myService = Substitute.For<IMyService>();
        }

        [TestMethod]
        public async Task TestMethod1()
        {
            _myService.SomeCall(Arg.Any<int>()).Returns(190);
            var output = await _apiCaller.Call(() => _myService.SomeCall(4));
            Assert.AreEqual(190, output);
        }
    }

    public class ApiCaller
    {
        public async Task<T> Call<T>(Func<T> service)
        {
            return await Task.Run(() => service.Invoke());
        }
    }

    public class MyService : IMyService
    {
        public int SomeCall(int x)
        {
            return x * 8;
        }
    }

    public interface IMyService
    {
        int SomeCall(int x);
    }

Because the mock is returning immediately, the call is not being actually awaited.

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