简体   繁体   English

使用Task对异步方法进行单元测试 <bool> 返回类型

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

I need to create a unit test for the following class's InvokeAsync method. 我需要为以下类的InvokeAsync方法创建一个单元测试。 What it merely does is calling a private method in the same class which includes complex logical branches and web service calls. 它只是在同一类中调用私有方法,该类包括复杂的逻辑分支和Web服务调用。 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. 如果您的测试框架支持它(MsTest支持),则可以声明您的测试方法async并从那里调用该方法。 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. 我会使用诸如Rhino Mocks之类的模拟框架来模拟Web服务,因此您不必依赖实际的Web服务。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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