6

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

在异步/等待方法的情况下使用 Assert.ThrowsException 有什么技巧?

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

3 回答 3

7

AFAICT,微软只是忘记包含它。它当然应该在 IMO 那里(如果您同意,请对 UserVoice 投票)。

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

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.");
    }
}
于 2012-11-30T02:57:11.917 回答
4

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

解决方案:解决此问题的另一种选择(@quango 也提到)是:

[TestMethod]
public void FooAsync_Test() {
    await Assert.ThrowsExceptionAsync<HttpRequestException>
    (async () => await _dataFetcher.GetDataAsync());
}
于 2020-07-03T15:18:28.860 回答
-2

以下对我来说很好:

Assert.ThrowsException<Exception>(() => class.AsyncMethod(args).GetAwaiter().GetResult());
于 2020-11-23T08:01:38.253 回答