Home > Coding > Unit testing async Functions in VS2012

Unit testing async Functions in VS2012

August 20th, 2012 Leave a comment Go to comments

In an attempt to get a jump start on writing Windows Store apps (is that what we’re calling them now?), I created a simple library targeting WinRT with some unit tests over the weekend. During that process, I got stumped for a good hour on how to properly write a unit test for an async function.

Let’s me walk you through this:

First: This is the code that I started with.

and I eventually found that you create your unit test like this

Note that the test itself is async and returns a Task. This is a requirement for the unit test. If the unit test returns void, you will not get a compile error, but the unit test will not show up in the Unit Test Explorer window.

The above code; however, doesn’t compile for a different reason.

The logic behind this is that you can only await something that returns a Task because of the way the framework works. The first hits in google said to do this:

Using the static function Run() against the function I wanted to execute would allow the test to wait on said function. Here’s where I ran into a peculiar issue (one which I, of course, cannot reproduce now that I’m trying to blog about it). It would compile and run, but when I hit the first await in the called function, the unit test would immediately return. Thus my test would always pass because no exception was thrown, no data every processed after the await, etc.

What I eventually discovered was that instead of wrapping the void function with Task.Run, I should make the function return Task instead:

After that update, my tests started waiting like they were supposed to.



Bonus:
There is a good follow up discussion on Stack Overflow about returning void vs returning a Task and what the purpose of even allowing an async void function is.

Categories: Coding Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.