Unlike similar AssertJ methods testing exceptions (assertThatCode()
, assertThatExceptionOfType()
, …), the
assertThatThrownBy()
method can be used alone, failing if the code did not raise any exception.
Still, only testing that an exception was raised is not enough to guarantee that it was the expected one, and you should test the exception type or
content further. In addition, it will make explicit what you are expecting, without relying on side-effects.
This rule raises an issue when assertThatThrownBy
is used, without testing the exception further.
Noncompliant code example
assertThatThrownBy(() -> shouldThrow()); // Noncompliant, is it really the exception you expected?
Compliant solution
assertThatThrownBy(() -> shouldThrow()).isInstanceOf(IOException.class);
//or
assertThatThrownBy(() -> shouldThrow()).hasMessage("My exception");