How does one test async code using MSTest

.NetUnit Testing

.Net Problem Overview


I'm writing some super simple async code. Just saving a file off-thread.

I'd like to test this code using the MSTest unit test framework in Microsoft Visual Studio Team System 2008.

How do I do this?

I'd like to simple block the test method until the method returns. I can imagine some ways to do this, but I'm blown away there aren't any best practices or helper classes around this.

I see a lot for Silverlight, but nothing generic.

.Net Solutions


Solution 1 - .Net

Visual studio 2012 (previously known as "Visual Studio 11") introduced support for async tests. It looks like this:

[TestMethod]
public async Task FooTest()
{
   var result = await SomeAsyncOperation();
   Assert.IsTrue(someCondition);
}

As noted in the comments, the Task return type is important. It won't work if you declare the method as returning void.

Solution 2 - .Net

Instead of calling the System.IO methods directly, try using the SystemWrapper library instead. Then in your tests you can mock out the calls as you wish, return whatever you like back to your test, including error conditions, and verify that your logic works as expected.

If you want to see an example, have a look at this blog post showing how it can be used with RhinoMocks.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin MooreView Question on Stackoverflow
Solution 1 - .NetWim CoenenView Answer on Stackoverflow
Solution 2 - .NetRichard BanksView Answer on Stackoverflow