AssertJ assertions allMatch
and doesNotContains
on an empty list always returns true whatever the content of the
predicate. Despite being correct, you should make explicit if you expect an empty list or not, by adding
isEmpty()
/isNotEmpty()
before calling the assertion. It will justify the useless predicate to improve clarity or increase
the reliability of the test.
This rule raises an issue when any of the methods listed are used without asserting that the list is empty or not.
Targetted methods:
allMatch
allSatisfy
doesNotContain
doesNotContainSequence
doesNotContainSubsequence
doesNotContainAnyElementsOf
List<String> logs = getLogs(); assertThat(logs).allMatch(e -> e.contains(“error”)); // Noncompliant, this test pass if logs are empty! assertThat(logs).doesNotContain("error"); // Noncompliant, do you expect any log?
List<String> logs = getLogs(); assertThat(logs).isNotEmpty().allMatch(e -> e.contains(“error”)); // Or assertThat(logs).hasSize(5).allMatch(e -> e.contains(“error”)); // Or assertThat(logs).isEmpty(); // Despite being redundant, this is also acceptable since it explains why you expect an empty list assertThat(logs).isEmpty().doesNotContain("error");