如何测试一个异步方法NUnit的,最终与另一个框架?框架、测试、方法、NUnit

2023-09-02 23:50:43 作者:她哭了你慌了我笑了

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

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)
    {
        ...
    }
}

我怎么能写NUnit的测试的ApiController的异步方法?如果我需要使用另一个测试框架,我开了这一点。我是相当新的一般的.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 既支持异步测试。

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);
    }
}
 
精彩推荐