如何使用 NUnit(或可能使用其他框架)测试异步方法?

编程入门 行业动态 更新时间:2024-10-24 18:27:45
本文介绍了如何使用 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 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 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(或可能使用其他框架)测试异步方法?

本文发布于:2023-11-03 16:29:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555582.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   或可   框架   测试   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!