本文介绍了xunit Assert.ThrowsAsync()无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个类似于以下的测试:

So I have a test like the following:

    [Fact]
    public void Test1()
    {
        Assert.ThrowsAsync<ArgumentNullException>(() => MethodThatThrows());
    }

    private async Task MethodThatThrows()
    {
        await Task.Delay(100);
        throw new NotImplementedException();
    }

令我惊讶的是,Test1成功通过。要使其失败,我必须这样写:

To my surprise, Test1 passes successfully. To make it fail I have to write like this:

Assert.Throws<ArgumentNullException>(() => MethodThatThrows().Wait());

如果ThrowsAsync()在上述情况下不起作用,它的目的是什么?

What is the purpose of ThrowsAsync(), if it does not work in the scenario above?

推荐答案

您应该 await 结果(请参阅)。

You're supposed to await the result (see xunit's acceptance tests).

[Fact] public async Task Test1()
{
    await Assert.ThrowsAsync<ArgumentNullException>(() => MethodThatThrows());
}

在这种特定的退化情况下,您只需 return Assert.ThrowsAsync 产生的 Task 而不使用 await ,但关键是您需要将生成的 Task 交还给xUnit框架,即

In this specific degenerate case, you could just return the Task that Assert.ThrowsAsync yields without using await, but the key thing is you need to hand the resulting Task back to the xUnit framework, i.e.

[Fact]
public Task Test1() =>
    Assert.ThrowsAsync<ArgumentNullException>(MethodThatThrows);

这篇关于xunit Assert.ThrowsAsync()无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 15:11