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

时间:2014-03-03 04:47:40

标签: c# unit-testing asynchronous

我需要为以下类 InvokeAsync 方法创建一个单元测试。它只是在同一个类中调用一个私有方法,包括复杂的逻辑分支和Web服务调用。但单元测试仅针对公共方法编写。那么在这种情况下我该怎么办?我应该在这里测试什么?任何建议都将不胜感激。

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.              
    }
}

1 个答案:

答案 0 :(得分:3)

如果您的测试框架支持它(MsTest),您可以声明您的测试方法async并从那里调用该方法。我使用模拟框架(例如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);
 }