我有一个 ASP.NET Web API 应用程序,带有一个具有异步方法的 ApiController,返回 Task<>
对象并标有 async
关键字。
public class MyApiController : ApiController
{
public async Task<MyData> GetDataById(string id)
{
...
}
}
如何为 ApiController 的异步方法编写 NUnit 测试?如果我需要使用另一个测试框架,我也愿意这样做。一般来说,我对 .NET 单元测试相当陌生,因此我有兴趣学习最佳实践。
最佳答案
截至今天(2014 年 7 月 2 日),异步测试支持:
- xUnit:with async methods that return a Task (since 1.9)
- MSTest:with async methods that return a Task (since VS 2012)
- NUnit:with async methods that return a Task, or even, that return void, since 2.6.2。由于不支持返回 void 的第 3.0 选项,如分析器错误 NUnit1012 The async test method must have a non-void return type 的文档所解释的那样。
在前两个框架中,测试方法必须具有以下签名:
[TestMethod]
public async Task MyTestMethod()
{
...
var result = await objectUnderTest.TestedAsyncMethod(...);
// Make assertions
}
NUnit v2.6.2+(但在 3.0 之前),除了该签名之外,还支持此签名:
public async void MyTestMethod()
当然,在任何这些测试方法中,您都可以使用 await
来调用和等待异步方法。
如果您使用的测试框架不支持异步测试方法,那么唯一的方法是调用异步方法并等待它使用任何常用方法完成运行: await
,使用 Result
的任何常用等待方法读取 Task<T>
方法返回的 async
的 Task
属性,依此类推。等待之后,您可以照常进行所有断言。例如,使用 MSTest:
[TestMethod]
public void MyTestMethod()
{
...
Task<MyResultClass> task = objectUnderTest.MyAsyncMethod(...);
// Make anything that waits for the method to end
MyResultClass result = task.Result;
// Make the assertions
Assert.IsNotNull(result);
...
}
关于.net - 如何使用 NUnit(或者可能使用其他框架)测试异步方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12191831/