【问题标题】:Strange behavior of NUnit async test with delegate带有委托的 NUnit 异步测试的奇怪行为
【发布时间】:2020-09-09 12:29:56
【问题描述】:

我在使用异步委托的 NUnit 测试中遇到了一个奇怪的行为。

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

谁能解释一下?

【问题讨论】:

    标签: c# .net async-await nunit


    【解决方案1】:

    这里的问题在于异步 void 回调。

    由于 'MyAsyncTest1' 使用 TestDelegate 并返回 void(变为 async void),因此无法正确处理异常。

    如果您在 'MyAsyncTest2' 测试中注意参数类型是 ActualValueDelegate 和 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());
            }
        } 
    

    【讨论】:

    • 但是为什么'MyAsyncTest2'的行为不同呢?为什么会通过?
    • 谢谢。现在我看到了不同的类型。
    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多