为什么包装异常消失

Why does the wrapping exception disappear

我不理解以下测试的行为(使用 xUnit.net 用 C# 编写)。我认为 ThrowsWrappingException 会通过,而 ThrowsCustomException 会失败。相反,它们具有相反的行为:ThrowsWrappingException 失败而 ThrowsCustomException 通过。

这是为什么?

[Fact]
public async Task ThrowsWrappingException() =>
  await Assert.ThrowsAsync<WrappingException>(InterceptException);

[Fact]
public async Task ThrowsCustomException() =>
  await Assert.ThrowsAsync<CustomException>(InterceptException);

private async Task InterceptException() {
  var task = ThrowCustomException();
  await Task.WhenAll(task);
  throw new WrappingException(task.Exception);
}

private Task ThrowCustomException() =>
  throw new CustomException();

private class WrappingException : Exception {
  public WrappingException(Exception e)
    : base(e.Message, e) { }
}

private class CustomException : Exception { }

这是因为

throw new WrappingException(task.Exception) 

永远不会被执行,因为您未处理的 CustomException 将被包装在 AggregateException 中并传播给调用者(单元测试),我猜这将解压缩它并检测到它是 CustomException,然后终止。

所以throw语句永远不会执行;你可以添加一个 try-catch 块来改变它。