简体   繁体   中英

Is it bad to have Unit Tests return async void?

I know it is bad practice to have a method return async void since it makes it hard to test, but is there any reason that a unit test needs to return async Task rather than async void?

Basically is this ok:

[Test()]
public async void MyTest()
{
    //Some code to run test
    //Assert Something
}

Or should I be doing this:

[Test()]
public async Task MyTest()
{
    //Some code to run test
    //Assert Something
}

To quote Async/Await - Best Practices in Asynchronous Programming By Stephen Cleary

Void-returning async methods have a specific purpose: to make asynchronous event handlers possible. It is possible to have an event handler that returns some actual type, but that doesn't work well with the language; invoking an event handler that returns a type is very awkward, and the notion of an event handler actually returning something doesn't make much sense. Event handlers naturally return void, so async methods return void so that you can have an asynchronous event handler. However, some semantics of an async void method are subtly different than the semantics of an async Task or async Task method.

Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started.

Those last few sentences sum it up nicely.

Long story short, use async Task for asynchronous test methods.

[Test()]
public async Task MyTest()
{
    //Some code to run test
    //Assert Something
}

You should really spend some time reading the linked article. It's author has a lot more resources in that subject matter and it will help you understand the semantics behind async/await

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM