102

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.

Daniel Mann
  • 53,152
  • 13
  • 97
  • 112
Kevin Moore
  • 5,274
  • 2
  • 28
  • 40
  • 4
    Duplicate? http://stackoverflow.com/questions/1174702/is-there-a-way-to-unit-test-an-async-method (I think the provided answers are not directly related to which testing framework that is used) – Fredrik Mörk Jan 13 '10 at 22:16
  • 1
    yes it is - and the answer will be the same I think. – Andras Zoltan Jan 13 '10 at 22:48

2 Answers2

190

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.

Spatz
  • 15,734
  • 6
  • 54
  • 57
Wim Coenen
  • 64,994
  • 13
  • 151
  • 241
  • 69
    Note that the `Task` return type is mandatory - `void` won't work (at least not on VS2013 update 4) – Ohad Schneider Dec 06 '14 at 18:52
  • 3
    (It will never work, since `void`-returning async methods cannot be awaited) – Richard Szalay Jul 17 '16 at 22:05
  • 1
    @RichardSzalay: it can be made to work, see here how NUnit does it: https://stackoverflow.com/questions/15031681/how-does-nunit-successfully-wait-for-async-void-methods-to-complete – Wim Coenen Aug 02 '16 at 15:07
-4

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.

Richard Banks
  • 12,346
  • 3
  • 45
  • 60