Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c# - Why can't "async void" unit tests be recognized?

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);
}

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See this answer for more discussion of async void vs async Task.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...