Search code examples
javaexceptionassertj

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


I want to assert that a certain exception (SSLHandshakeException) is thrown when running some code.

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

However, this fails because the failure trace says:

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

Checking on ProcessingException would work, but is too general. I need to make sure that the code snippet fails because of SSL handshake.

How can I change it in a way that the "second" exception should be considered?


Solution

  • You can simply use hasCauseInstanceOf.