简体   繁体   中英

NUnit 3.X.X async test

I am trying to unit test an async task with 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.

As per my understanding, the new nUnit framework requires to return either Task or Task<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:

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. Async test methods must return Task if no value is returned, or Task if a value of type T is returned.

If the test method returns a value, you must pass in the ExpectedResult named parameter to the Test attribute. 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()
{ /* ... */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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