异步函数单元测试中的Assert.ThrowsException?

时间:2012-11-29 21:09:20

标签: visual-studio unit-testing assert

我尝试制作测试方法来测试一些简单的数据下载。我做了一个测试用例,其中下载应该通过HttpRequestException失败。在测试其非异步版本时,测试工作得很好并通过,但在测试其asnyc版本时,它会失败。

在async / await方法的情况下使用Assert.ThrowsException有什么诀窍?

[TestMethod]
    public void FooAsync_Test()
    {
        Assert.ThrowsException<System.Net.Http.HttpRequestException>
(async () => await _dataFetcher.GetDataAsync());
    }

3 个答案:

答案 0 :(得分:6)

AFAICT,微软只是忘了把它包括在内。它当然应该在IMO(如果你同意,vote on UserVoice)。

与此同时,您可以使用以下方法。它来自my AsyncEx library中的AsyncAssert类。我计划在不久的将来发布AsyncAssert作为NuGet库,但是现在你可以把它放在你的测试类中:

public static async Task ThrowsAsync<TException>(Func<Task> action, bool allowDerivedTypes = true)
{
    try
    {
        await action();
        Assert.Fail("Delegate did not throw expected exception " + typeof(TException).Name + ".");
    }
    catch (Exception ex)
    {
        if (allowDerivedTypes && !(ex is TException))
            Assert.Fail("Delegate threw exception of type " + ex.GetType().Name + ", but " + typeof(TException).Name + " or a derived type was expected.");
        if (!allowDerivedTypes && ex.GetType() != typeof(TException))
            Assert.Fail("Delegate threw exception of type " + ex.GetType().Name + ", but " + typeof(TException).Name + " was expected.");
    }
}

答案 1 :(得分:3)

上下文:根据您的描述,您的测试失败。

解决方案:解决此问题的另一种方法(也由@quango提及)是

[TestMethod]
public void FooAsync_Test() {
    await Assert.ThrowsExceptionAsync<HttpRequestException>
    (async () => await _dataFetcher.GetDataAsync());
}

答案 2 :(得分:-1)

以下对我来说很好:

Assert.ThrowsException<Exception>(() => class.AsyncMethod(args).GetAwaiter().GetResult());