如何使用 MSTest 测试异步代码

我在写一些超级简单的异步代码,只是在线程外保存一个文件。

我想使用 MicrosoftVisualStudioTeamSystem2008中的 MSTest 单元测试框架来测试这段代码。

我该怎么做?

我想简单地阻塞测试方法,直到该方法返回。我可以想象一些方法来做到这一点,但我感到惊讶的是,在这方面没有任何最佳实践或帮助类。

我看到了 Silverlight 的 很多,但没有通用的。

27170 次浏览

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.