我尝试做一个测试方法来测试一些简单的数据下载。我做了一个测试用例,其中下载应该失败并出现 HttpRequestException。当测试其非异步版本时,测试效果很好并且通过,但是当测试其 asnyc 版本时,它失败了。
在 async/await 方法中使用 Assert.ThrowsException 有什么技巧?
[TestMethod]
public void FooAsync_Test()
{
Assert.ThrowsException<System.Net.Http.HttpRequestException>
(async () => await _dataFetcher.GetDataAsync());
}
上下文:根据您的描述,您的测试失败。
解决方案:解决此问题的另一种替代方案(@quango 也提到过)是:
[TestMethod]
public void FooAsync_Test() {
await Assert.ThrowsExceptionAsync<HttpRequestException>(() => _dataFetcher.GetDataAsync());
}
使用 xUnit 的解决方案:
[Fact]
public async void FooAsync_Test() {
await Assert.ThrowsAsync<HttpRequestException>(() => _dataFetcher.GetDataAsync());
}
AFAICT,微软只是忘了包含它。 IMO 肯定应该有(如果您同意,在 UserVoice 上投票)。
同时,您可以使用以下方法。它来自
我的 AsyncEx 库中的
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.");
}
}
以下对我来说效果很好:
Assert.ThrowsException<Exception>(() => class.AsyncMethod(args).GetAwaiter().GetResult());