如何使用 NUnit(或可能使用其他框架)测试异步方法? [英] How do I test an async method with NUnit (or possibly with another framework)?

查看:29
本文介绍了如何使用 NUnit(或可能使用其他框架)测试异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET Web API 应用程序,带有一个具有异步方法的 ApiController,返回 Task<> 对象并用 async 关键字标记.>

I have an ASP.NET Web API application, with an ApiController that features asynchronous methods, returning Task<> objects and marked with the async keyword.

public class MyApiController : ApiController
{
    public async Task<MyData> GetDataById(string id)
    {
        ...
    }
}

如何为 ApiController 的异步方法编写 NUnit 测试?如果我需要使用另一个测试框架,我也愿意.总的来说,我对 .NET 单元测试还很陌生,所以我对学习最佳实践很感兴趣.

How can I write NUnit tests for the ApiController's asynchronous methods? If I need to use another testing framework I'm open for that too. I'm fairly new to .NET unit testing in general, so I'm interested in learning best practices.

推荐答案

在我看来,NUnit 2.6 中似乎不支持测试返回任务的异步方法.我现在能看到的最佳选择是使用 Visual Studio 自己的 UnitTesting 框架或 xUnit.net as都支持异步测试.

It seems to me there is no support built into NUnit 2.6 for testing async methods returning Tasks. The best option I can see right now is to use Visual Studio's own UnitTesting framework or xUnit.net as both support asynchronous tests.

使用 Visual Studio UnitTesting 框架,我可以编写这样的异步测试:

With the Visual Studio UnitTesting framework I can write asynchronous tests like this:

using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class TestAsyncMethods
{
    [TestMethod]
    public async Task TestGetBinBuildById()
    {
         ...
         var rslt = await obj.GetAsync();
         Assert.AreEqual(rslt, expected);
    }
}

这篇关于如何使用 NUnit(或可能使用其他框架)测试异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆