Async Unit Tests in Visual Studio 2012
Posted by riwalk on 12 Dec 2012 | Tagged as: C#, Testing
If you’re trying to do unit testing using async functions in Visual Studio 2012, you may be in for a surprise.
For example, lets start with a very simple test project like this:
Nice and simple.
When I run the test, I am greeted with a pleasant green checkmark:
Now I’m going to make a small change to the test above:
All I’ve done is changed the code to run the add operation asynchronously. Now when I go to the run the tests, the Test Explorer window gives a not-so-pleasant message:
Build your solution to discover all available tests. Click "Run All" to build, discover, and run all tests in your solution.
So what gives?
It turns out that if you want to unit test an asynchronous method, it needs to return a “Task” object. There are no warnings from Visual Studio. You’re just supposed to “know.”
Change the code to this:
And lo and behold:
The checkmark we love so dearly returns.
4 Comments »
Thanks for the explanation! I struggled with this yesterday and now I’m sorted. Cheers 🙂
Thanks for your article. I didn’t know why my asynchronous Tests didn’t wanted to show up in my Test Explorer, but with the simple addition of “Task” they did.
Thank you!!!
Thanks a ton!