如何在抛出 "Exception A: Exception B" 时断言 'Exception B'?

How to assert 'Exception B' when "Exception A: Exception B" is thrown?

我想断言 运行 某些代码时抛出某个异常 (SSLHandshakeException)。

assertThatThrownBy(() -> {
        // some code
    }).isInstanceOf(SSLHandshakeException.class);

但是,这失败了,因为失败跟踪显示:

java.lang.AssertionError: 
Expecting:
  <javax.ws.rs.ProcessingException: javax.net.ssl.SSLHandshakeException:     Received fatal alert: handshake_failure>
to be an instance of:
  <javax.net.ssl.SSLHandshakeException>
but was:
  <"javax.ws.rs.ProcessingException: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

检查 ProcessingException 会起作用,但过于笼统。我需要确保代码片段因 SSL 握手而失败。

如何更改它以考虑 "second" 异常?

一个getCause()应该有助于这里访问内部异常。

assertThatThrownBy(() -> {
        // some code
    }).getCause().isInstanceOf(SSLHandshakeException.class);

您可以简单地使用 hasCauseInstanceOf