【问题标题】:Flurl & xUnit doesn't Catch Exception using awaitFlurl & xUnit 不使用等待捕获异常
【发布时间】:2019-01-27 09:39:54
【问题描述】:

我正在为 WebAPI 设置使用者并编写一些单元测试。我的测试的“行为”部分如下:

var dta = await service.AuthenticateAsync(customerId, userName, password, machineId);           

try
{
    service.AuthenticateAsync(customerId, userName, password, machineId).Wait();
}
catch (AggregateException ex)
{
    exUnauthorized = ex;
}
try
{
    httpTest.SimulateTimeout();
    await service.AuthenticateAsync(customerId, userName, password, machineId);
 }
 catch (AggregateException ex)
 {
     exTimeout = ex;
 }

我设置 Flurl HttpTest 如下:

httpTest.RespondWithJson(auth)
                .RespondWith(status: (int)HttpStatusCode.Unauthorized);

为了获得成功的第一个响应和未经授权的第二个响应。正如您稍后在代码中看到的那样,我设置了超时来测试它(如果我最初设置它,它似乎对所有请求都超时)。

第一次调用成功。我在 try 块中使用 Wait() 的第二个调用起作用并捕获了聚合异常。我使用await 的第二次调用没有捕获异常;单元测试失败,方法抛出异常。

我错过了什么?为什么 await 调用不能正常工作?

【问题讨论】:

  • await unwraps the exception,只要捕获你的方法抛出的异常
  • 当.. 当我错过一些非常简单的事情时,我讨厌它:)。谢谢!让它成为答案,我会接受。
  • 投反对票,我用谷歌搜索了一段时间,没有找到任何东西,抱歉。获得否决票的问题有什么问题?

标签: c# async-await xunit flurl


【解决方案1】:

await 不会将异常包装在AggregateException 中,因为它旨在用于异步代码。 Wait() 和 Result 确实将底层异常包装在 AggregateException 中,因为它们旨在用于并行代码。

从技术上讲,await unwraps 并不是例外;它只是 不包装 它就像 Wait/Result 那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 2014-12-01
    • 2014-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    相关资源
    最近更新 更多