如何处理任务中的xUnit .NET的Assert.Throws&LT抛出的异常; T&GT ;? [英] How to handle exceptions thrown by Tasks in xUnit .net's Assert.Throws<T>?
问题描述
与的λ
标记有异步<以下异步
xUnit.net
测试/ code>修改通过报告,没有异常被抛出失败:
The following asynchronous xUnit.net
test with a lambda
marked with the async
modifier fails by reporting that no exception was thrown:
[Theory, AutoWebData]
public async Task SearchWithNullQueryThrows(
SearchService sut,
CancellationToken dummyToken)
{
// Fixture setup
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(async () =>
await sut.SearchAsync(null, dummyToken));
// Teardown
}
要确保一个 ArgumentNullException
实际上是扔我明确地使用了的try-catch
块。它的工作,然而所得到的code是不干净(相比于第一测试):
To make sure that an ArgumentNullException
is actually thrown I explicitly used a try-catch
block. It worked, however the resulting code is not clean (compared to the first test):
[Theory, AutoWebData]
public async Task SearchWithNullQueryThrows(
SearchService sut,
CancellationToken dummyToken)
{
// Fixture setup
var expected = typeof(ArgumentNullException);
Type actual = null;
// Exercise system
try
{
await sut.SearchAsync(null, dummyToken);
}
catch (ArgumentNullException e)
{
actual = e.GetType();
}
// Verify outcome
Assert.Equal(expected, actual);
// Teardown
}
为什么 Assert.Throws&LT; T&GT;
与的λ
标记有异步
修改失败?
推荐答案
更新
这已经解决了的xUnit 2,增加的 Assert.ThrowsAsync
。
This has been solved in xUnit 2, with the addition of Assert.ThrowsAsync
.
我怀疑 Assert.Throws
未异步
-Aware。我建议提高这个问题与团队的xUnit,提示 ThrowsAsync
添加。
I am suspecting that Assert.Throws
is not async
-aware. I recommend raising this issue with the xUnit team, suggesting a ThrowsAsync
be added.
这是异步
委托在这种情况下返回工作
或任务&LT; T&GT;
和 ArgumentNullException
不是抛出的代表直接;相反,它被放置在工作
( Task.Exception.InnerException
)。 Assert.Throws
是预期的异常直接抛出的代表,而不是放置在返回值的属性。
An async
delegate in this case is returning Task
or Task<T>
, and the ArgumentNullException
is not thrown out of the delegate directly; instead, it is placed on the Task
(Task.Exception.InnerException
). Assert.Throws
is expecting the exception to be thrown out of the delegate directly, not placed on a property of the return value.
您可以创建自己的 AssertEx.ThrowsAsync
这样:
You can create your own AssertEx.ThrowsAsync
as such:
public static async Task ThrowsAsync<TException>(Func<Task> func)
{
var expected = typeof(TException);
Type actual = null;
try
{
await func();
}
catch (Exception e)
{
actual = e.GetType();
}
Assert.Equal(expected, actual);
}
其可以用作这种
[Theory, AutoWebData]
public async Task SearchWithNullQueryThrows(
SearchService sut,
CancellationToken dummyToken)
{
// Fixture setup
// Exercise system and verify outcome
await AssertEx.ThrowsAsync<ArgumentNullException>(async () =>
await sut.SearchAsync(null, dummyToken));
// Teardown
}
我在使用MSTest的类似的方法。
I use a similar approach in MSTest.
这篇关于如何处理任务中的xUnit .NET的Assert.Throws&LT抛出的异常; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!