rspec/rules/S5841/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

66 lines
1.9 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

== Why is this an issue?
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()++`` in addition to calling the assertion, or by testing the list's content further. 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 and without testing the content.
Targetted methods:
* ``++allMatch++``
* ``++allSatisfy++``
* ``++doesNotContain++``
* ``++doesNotContainSequence++``
* ``++doesNotContainSubsequence++``
* ``++doesNotContainAnyElementsOf++``
=== Noncompliant code example
[source,java]
----
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?
----
=== Compliant solution
[source,java]
----
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).doesNotContain("error").isEmpty();
// or test the content of the list further
assertThat(logs).contains("warning").doesNotContain("error");
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Test the emptiness of the list before calling this assertion predicate.
=== Highlighting
* Primary: allMatch/doesNotContains
* Secondary: tested list
endif::env-github,rspecator-view[]