问题描述
async void
单元测试不能在 Visual Studio 2012 中运行:
async void
unit tests cannot be run within Visual Studio 2012:
[TestClass]
public class MyTestClass
{
[TestMethod]
public async void InvisibleMyTestMethod()
{
await Task.Delay(1000);
Assert.IsTrue(true);
}
}
如果我想进行异步单元测试,测试方法必须返回一个任务:
If I want to have an asynchronous unit test, the test method has to return a Task:
[TestMethod]
public async Task VisibleMyTestMethod()
{
await Task.Delay(1000);
Assert.IsTrue(true);
}
为什么会这样?并不是说我绝对需要一个 async void
测试方法,我只是很好奇.当您构建 async void
测试方法时,Visual Studio 2012 不会发出警告或错误,即使它无法运行...
Why is it so? Not that I absolutely need to have an async void
test method, I am just curious. Visual Studio 2012 gives no warning nor error when you build an async void
test method even though it won't be able to be run...
推荐答案
async void
方法应该被视为即发即弃"——没有办法等待它们完成.如果 Visual Studio 启动这些测试之一,它将无法等待测试完成(将其标记为成功)或捕获引发的任何异常.
async void
methods should be considered as "Fire and Forget" - there is no way to wait for them to finish. If Visual Studio were to start one of these tests, it wouldn't be able to wait for the test to complete (mark it as successful) or trap any exceptions raised.
使用 async Task
,调用者能够等待执行完成,并捕获运行时引发的任何异常.
With an async Task
, the caller is able to wait for execution to complete, and to trap any exceptions raised while it runs.
请参阅此答案,了解关于async void
与async Task代码>.
See this answer for more discussion of async void
vs async Task
.
这篇关于为什么不能“异步无效"?单元测试被认可?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!