[英]Error `Async test method must have non-void return type` when upgrading from NUnit 2 to NUnit 3
I have to refactor am unit test from NUNIT 2 to NUNIT 3 and the following syntax throws an error:我必须将单元测试从 NUNIT 2 重构为 NUNIT 3,以下语法会引发错误:
var expectedResponseMessage = new HttpResponseMessage();
Func<Task<HttpResponseMessage>> continuation =
() => Task.Factory.StartNew(() => expectedResponseMessage);
Error:错误:
Async test method must have non-void return type
异步测试方法必须具有非 void 返回类型
How may I rewrite this?我该如何重写? I have tried many syntaxes but no luck.
我尝试了很多语法,但没有运气。
The error错误
Async test method must have non-void return type
异步测试方法必须具有非 void 返回类型
means that in NUnit 3+, an async
Unit Test itself may not have a void
return type (ie the method decorated with [Test] / [TestCase]
etc).意味着在 NUnit 3+ 中,
async
单元测试本身可能没有void
返回类型(即用[Test] / [TestCase]
等装饰的方法)。 Instead, you can return an empty Task
( Correct way in newer versions of NUnit with async test support ):相反,您可以返回一个空
Task
(在具有异步测试支持的较新版本的 NUnit 中的正确方法):
[Test]
public async Task EnsureFoo()
{
// Arrange
// Act
var myResult = await classBeingTested.DoSomethingAsync();
// Assert
Assert.IsNotNull(myResult);
...
}
In NUnit 2.x, this wasn't checked, so a async void
unit test could slip into your unit test code base, ie of the form ( Bad, don't do this )在 NUnit 2.x 中,这没有被检查,因此
async void
单元测试可能会滑入您的单元测试代码库,即形式(糟糕,不要这样做)
[Test]
public async void Foo() // < -- Error : Async test method must have non-void return type
{
var myResult = await classBeingTested.DoSomethingAsync();
// Post continuation assertions here.
}
this is rather dangerous - the test can't be awaited * , and would return before any continuations completed - eg any failures in the Asserts
done in the continuation might not be reported.这是相当危险的 - 测试不能等待* ,并且会在任何延续完成之前返回 - 例如,可能不会报告延续中完成的
Asserts
中的任何失败。
Re : Your fake Task Re: 你的假任务
Scheduling a Task just to return a fake response seems overkill, ie in most tests you should be able to use Task.FromResult
to replace:安排一个任务只是为了返回一个假响应似乎
Task.FromResult
矫枉过正,即在大多数测试中你应该能够使用Task.FromResult
来替换:
Func<Task<HttpResponseMessage>> continuation =
() => Task.Factory.StartNew(() => expectedResponseMessage);
With the cheaper:用更便宜的:
Func<Task<HttpResponseMessage>> continuation =
() => Task.FromResult(expectedResponseMessage);
Task.FromResult
returns an already completed task with the given return value - in most cases, this should suffice for your unit testing purposes, unless you really do want an independent Task to be executed on the threadpool. Task.FromResult
使用给定的返回值返回一个已经完成的任务 - 在大多数情况下,这应该足以满足您的单元测试目的,除非您确实希望在Task.FromResult
执行一个独立的任务。
* Actually, seemingly even earlier versions such as NUnit 2.6.4 had already identified the issue with async void
tests, and incorporated a workaround * 实际上,似乎更早的版本(例如 NUnit 2.6.4)已经发现
async void
测试的问题,并采用了解决方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.