Why can't “async void” unit tests be recognized?

China☆狼群 提交于 2019-11-27 18:54:51
Richard

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.

Stephen Cleary

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.

I found in VS2015 that any Test methods decorated with async would not show in Test Explorer. I ended up removing the async keyword and replacing the await call in the test with a task.Wait() and done my asertions on task.Result.

Seems to be working ok. Haven't tried it with exception testing yet.

var task = TheMethodIWantToTestAsync(someValue);
task.Wait();
var response = task.Result;

Assert.IsNotNull(response);
Assert.IsTrue(response.somevalue);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!