Java

Java

Made by DeepSource

Avoid catching assertions in tests JAVA-W1076

Bug risk
Critical

Avoid catching assertion exceptions, they are meant to indicate that something should not have happened.

This can happen when there is a catch block for Throwable or Error, or if one tries to directly catch an AssertionError or its descendents.

Because Throwable is the parent of all exception and error types, and even assertion failures are represented as thrown Errors, it is inadvisable to catch either of Throwable or Error in a test.

Bad Practice

try {
    assertTrue(someCondition);
} catch (Throwable e) { // Don't catch Throwable in tests!
    // ...
}

Recommended

Avoid catching overly generic exception types such as Throwable or Error, and do not attempt to catch AssertionErrors.

If you really require generic exception handling within a test, catch only Exceptions.

try {
    assertTrue(someCondition);
} catch (Exception e) {  // this will not interfere with assertions.
    // ...
}