为什么不能"异步无效"单元测试的认可? [英] Why can't "async void" unit tests be recognized?

查看:197
本文介绍了为什么不能"异步无效"单元测试的认可?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步无效单元测试不能内运行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);
}

为什么会这样呢?这并不是说我绝对需要有一个异步无效测试方法,我只是好奇。的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...

推荐答案

异步无效方法应被视为射后不理 - 有没有办法等待他们完成。如果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.

随着异步任务,来电者能够等待执行完成,而它运行到捕获任何异常升高。

With an async Task, the caller is able to wait for execution to complete, and to trap any exceptions raised while it runs.

请参阅这个答案的异步无效更多的讨论 VS 异步任务

这篇关于为什么不能"异步无效"单元测试的认可?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆