简体   繁体   English

NUnit 3.XX异步测试

[英]NUnit 3.X.X async test

I am trying to unit test an async task with NUnit 3.12.0.0. 我正在尝试使用NUnit 3.12.0.0对异步任务进行单元测试。 The problem is I keep getting the following: Message: Async test method must have non-generic Task return type when no result is expected and my test fails. 问题是我不断收到以下消息:消息: 当预期没有结果且测试失败时,异步测试方法必须具有非通用的任务返回类型 The code below was actually working with Visual Studio 2017 and an older version of nUnit. 下面的代码实际上与Visual Studio 2017和较旧版本的nUnit一起使用。

As per my understanding, the new nUnit framework requires to return either Task or Task<T> . 据我了解,新的nUnit框架需要返回TaskTask<T>

This is my test function 这是我的测试功能

[Test]
public async Task<string> Login()
{
    var url = "http://localhost:xxxx/login";
    object[] jsonBody = { "{\"username\":\"devTeam@xxxxxxxxx.com\",\"password\":\"xxxx\"}" };

    RestRequestResponse<RestResponse> result = await HttpRestUtil.ExecuteCompleteRestRequest<RestResponse>(url, null, jsonBody, Method.POST);
    Assert.IsNotNull(result);
    Assert.IsNotNull(result.headers[0].Value.ToString());
    return result.headers[0].Value.ToString();
}

I have found the answer to my question. 我找到了我问题的答案。 The answer is from the NUnit documentation which states the following: 答案来自NUnit文档,其中指出以下内容:

Test methods targeting .Net 4.0 or higher may be marked as async and NUnit will wait for the method to complete before recording the result and moving on to the next test. 面向.Net 4.0或更高版本的测试方法可能被标记为异步,并且NUnit将在记录结果并进行下一个测试之前等待该方法完成。 Async test methods must return Task if no value is returned, or Task if a value of type T is returned. 如果没有返回值,则异步测试方法必须返回Task;如果返回类型T的值,则异步测试方法必须返回Task。

If the test method returns a value, you must pass in the ExpectedResult named parameter to the Test attribute. 如果测试方法返回值,则必须将ExpectedResult命名参数传递给Test属性。 This expected return value will be checked for equality with the return value of the test method. 将检查此预期的返回值是否与测试方法的返回值相等。

This is an example: 这是一个例子:

// Async test with an expected result
[Test(ExpectedResult = 4)]
public async Task<int> TestAdd()
{
    await ...
    return 2 + 2;
}


// A simple async test
[Test]
public async Task AddAsync()
{ /* ... */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM