How does one test async code using MSTest

前端 未结 2 435
萌比男神i
萌比男神i 2020-12-13 11:55

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

相关标签:
2条回答
  • 2020-12-13 12:19

    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.

    0 讨论(0)
  • 2020-12-13 12:31

    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.

    0 讨论(0)
提交回复
热议问题