简体   繁体   中英

Unit testing an async method with Task<bool> return type

I need to create a unit test for the following class's InvokeAsync method. What it merely does is calling a private method in the same class which includes complex logical branches and web service calls. But the unit test are written only for the public methods. So what should I do in this scenario? What should I test in here? Any suggestions would be greatly appreciated.

public class MyCustomHandler
{
    private readonly ILogger _logger;
    private readonly HttpClient _httpClient;

    public MyCustomHandler(HttpClient client, ILogger logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public override async Task<bool> InvokeAsync()
    {
        return await InvokeReplyPathAsync();
    }

    private async Task<bool> InvokeReplyPathAsync()
    {
        // Lot of code with complex logical branches and calling web services.              
    }
}

If your testing framework supports it (MsTest does) you can declare your test method async and call the method from there. I'd mock the web services using a mock framework such as Rhino Mocks so you don't need to depend on the actual web service.

public interface IWebService
{
    Task<bool> GetDataAsync();
}

[TestClass]
public class AsyncTests
{
    [TestMethod]
    public async void Test()
    {
        var webService = MockRepository.GenerateStub<IWebService>();
        webService.Expect(x => x.GetDataAsync()).Return(new Task<bool>(() => false));

        var myHandler = new MyCustomHandler(webService);
        bool result = await myHandler.InvokeAsync();
        Assert.IsFalse(result);
    }
}

[TestMethod]
public async void TestWebServiceException()
{
    var webService = MockRepository.GenerateStub<IWebService>();
    webService.Expect(x => x.GetDataAsync()).Throw(new WebException("Service unavailable"));

    var myHandler = new MyCustomHandler(webService);
    bool result = await myHandler.InvokeAsync();
    Assert.IsFalse(result);
 }

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