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

Strange behavior of NUnit async test with delegate

我 运行 进入了具有异步委托的 NUnit 测试的 st运行ge 行为。

MyAsyncTest,我事先声明委托的地方失败了 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());
}

谁能解释一下?

这里的问题出在 async void 回调中。

由于'MyAsyncTest1'使用TestDelegate并且return无效(它变成异步无效),它不能正确处理异常。

如果你在 'MyAsyncTest2' 中注意测试参数的类型是 ActualValueDelegate with Task return 类型(意味着异常将被正确处理)。

要解决此问题,您必须明确指定 return 类型为任务。请参阅提供的示例。

    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());
        }
    }