簡體   English   中英

在異步方法中測試異常

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

代碼沒有捕捉到異常,並且失敗了

預期會引發 System.Exception,但未引發異常。

我確定我遺漏了一些東西,但文檔似乎暗示這是要走的路。 一些幫助將不勝感激。

您應該使用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());

使用 Fluent Assertions v5.7 ,他們引入了Awaiting重載,因此現在您可以執行以下操作:

public async void TestFail()
{
    await this.Awaiting(_ => Fail()).Should().ThrowAsync<Exception>();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM