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...
Async void methods can wreak havoc if the caller isn't expecting them to be async. When the return type is Task, the caller knows it's dealing with a future operation; when the return type is void, the caller might assume the method is complete by the time it returns.
In short, if your async method is an event handler or a callback, it's ok to return void .
Async unit tests that return Task have none of the problems of async unit tests that return void. Async unit tests that return Task enjoy wide support from almost all unit test frameworks.
An async void method will capture the current SynchronizationContext at the beginning of the method, and any exceptions from that method will be captured and raised directly on that captured context. In the most common scenarios, this will cause an application-level exception, usually a crash.
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
.
It's just because MSTest doesn't support async void
unit tests. It is possible to do so by introducing a context in which they can execute.
MSTest doesn't support this, probably because Microsoft decided it was too much of a change for existing tests (it's possible that existing tests would deadlock if they were given an unexpected context).
There's no compiler warning/error because it's perfectly valid C# code. The only reason it doesn't work is because of the unit test framework (i.e., I believe that xUnit does support async void
tests), and it would be a gross violation of separation of concerns for the C# compiler to look at your attributes, determine you are using MSTest, and decide that you really didn't want to use async void
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With