简体   繁体   English

使用委托进行 NUnit 异步测试的奇怪行为

[英]Strange behavior of NUnit async test with delegate

I ran into a strange behavior of NUnit tests with async delegates.我遇到了带有异步委托的 NUnit 测试的奇怪行为。

MyAsyncTest , where I declare the delegate beforehand, fails with System.ArgumentException : Async void methods are not supported. Please use 'async Task' instead.我事先声明委托的MyAsyncTestSystem.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 , where I paste delegate right in, passes.我在其中粘贴委托的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());
}

Can someone explain?有人可以解释一下吗?

The problem here is in async void callbacks.这里的问题在于异步 void 回调。

Since 'MyAsyncTest1' uses TestDelegate and it returns void(it becomes async void), it can't handle Exception properly.由于 'MyAsyncTest1' 使用TestDelegate并且它返回 void(它变成 async void),它不能正确处理异常。

If you pay attention in 'MyAsyncTest2' test the type of argument is ActualValueDelegate with Task return type (meaning the Exception will be handled correctly).如果您在 'MyAsyncTest2' 测试中注意参数类型是 ActualValueDelegate 和 Task 返回类型(意味着异常将被正确处理)。

To fix the issue you have to explicitly specify the return type to be Task.要解决此问题,您必须明确指定返回类型为 Task。 See provided example.请参阅提供的示例。

    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.

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