测试异步方法中的异常

Testing for exceptions in async methods

我对这段代码有点困惑(这是一个示例):

public async Task Fail()
{
    await Task.Run(() => { throw new Exception(); });
}

[Test]
public async Task TestFail()
{
    Action a = async () => { await Fail(); };
    a.ShouldThrow<Exception>();
}

代码没有捕捉到异常,并失败并显示

Expected a System.Exception to be thrown, but no exception was thrown.

我确定我遗漏了一些东西,但文档似乎建议这是要走的路。一些帮助将不胜感激。

你应该使用 Func<Task> 而不是 Action:

[Test]
public void TestFail()
{
    Func<Task> f = async () => { await Fail(); };
    f.ShouldThrow<Exception>();            
}

这将调用以下用于验证异步方法的扩展

public static ExceptionAssertions<TException> ShouldThrow<TException>(
    this Func<Task> asyncAction, string because = "", params object[] becauseArgs)
        where TException : Exception        

在内部,此方法将 运行 由 Func 返回的任务并等待它。像

try
{
    Task.Run(asyncAction).Wait();
}
catch (Exception exception)
{
    // get actual exception if it wrapped in AggregateException
}

注意测试本身是同步的。

使用 Fluent Assertions v5+ 后的代码将如下所示:

ISubject sut = BuildSut();
//Act and Assert
Func<Task> sutMethod = async () => { await sut.SutMethod("whatEverArgument"); };
await sutMethod.Should().ThrowAsync<Exception>();

这应该有效。

使用 ThrowAsync 方法的其他变体:

await Should.ThrowAsync<Exception>(async () => await Fail());