Unit testing async/await with VS2012 and later

Leave it to me to try the most complex solution first, and then later realize there was a far easier way to do it! OK, so I’m trying to develop a higher-quality version of an OWIN provider to work with ASP.NET, for use in new projects, going forward. Just about all of OWIN uses the notorious async/await pattern.

What I ended up with was something like this, for a unit test:

 

It looks like it should work, and voila – my tests run green. Wait a minute, all my tests run green – even ones that should fail!

It turns out that the Assert statements do get run, but not in the context of the unit test. Presumably, they are executed in another thread, so the unit test never catches the assertion!

After a little investigating, it turns out I was overthinking this.

MSTest from VS2012 onward supports async/await. The only catch is the the unit test can’t have a void return type, it must return a task.

So, if I refactor the test into something like this:

and ironically, I found a bug in the unit test, the second assert should have been IsFalse(..). Now that can async/await and actually get assertions, I now have successful, and simplified unit tests!

Posted in Uncategorized, Unit Testing, Visual Studio

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives
Categories

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 2 other followers

%d bloggers like this: