![](/img/trans.png)
[英]WPF Dispatcher.InvokeAsync() strange behavior with async delegate
[英]Strange behavior of NUnit async test with delegate
我遇到了带有异步委托的 NUnit 测试的奇怪行为。
我事先声明委托的MyAsyncTest
因System.ArgumentException : Async void methods are not supported. Please use 'async Task' instead.
失败System.ArgumentException : Async void methods are not supported. Please use 'async Task' instead.
System.ArgumentException : Async void methods are not supported. Please use 'async Task' instead.
我在其中粘贴委托的MyAsyncTest2
通过了。
[Test] //fails
public void MyAsyncTest()
{
TestDelegate testDelegate = async () => await MyTestMethod();
Assert.That(testDelegate, Throws.Exception);
}
[Test] //passes
public void MyAsyncTest2()
{
Assert.That(async () => await MyTestMethod(), Throws.Exception);
}
private async Task MyTestMethod()
{
await Task.Run(() => throw new Exception());
}
有人可以解释一下吗?
这里的问题在于异步 void 回调。
由于 'MyAsyncTest1' 使用TestDelegate并且它返回 void(它变成 async void),它不能正确处理异常。
如果您在 'MyAsyncTest2' 测试中注意参数类型是 ActualValueDelegate 和 Task 返回类型(意味着异常将被正确处理)。
要解决此问题,您必须明确指定返回类型为 Task。 请参阅提供的示例。
public class Tests
{
[Test]
public void MyAsyncTest()
{
Func<Task> testDelegate = async () => await MyTestMethod();
Assert.That(testDelegate, Throws.Exception);
}
private async Task MyTestMethod()
{
await Task.Run(() => throw new Exception());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.