xunit Assert.ThrowsAsync()不能正常工作?

时间:2016-11-27 11:14:09

标签: .net unit-testing asynchronous xunit.net

所以我有如下测试:

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

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

令我惊讶的是,Test1成功通过。为了让它失败,我必须这样写:

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

ThrowsAsync()的目的是什么,如果它在上面的场景中不起作用?

2 个答案:

答案 0 :(得分:45)

你应该await结果(见xunit's acceptance tests)。

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

在这个特定的简并案例中,您可以return Task Assert.ThrowsAsyncawait不使用Task,但关键是您需要提交[Fact] public Task Test1() => Assert.ThrowsAsync<ArgumentNullException>(MethodThatThrows); { {1}}回到xUnit框架,即

{
    "name": "root/stack-overflow",
    "minimum-stability": "stable",
    "require": {
        "filp/whoops": "1.*"
    }
}

答案 1 :(得分:2)

只要有人想分开“行为”和“断言”部分,就可以使用以下代码:

//Act
Task result() => systemUnderTest.AsyncMethodThatThrows();

//Assert
await Assert.ThrowsAsync<Exception>(result);