Assertions comparing an object to itself are more likely to be bugs due to developer’s carelessness.
This rule raises an issue when the actual expression matches the expected expression.
assertThat(actual).isEqualTo(actual); // Noncompliant
assertThat(actual).isEqualTo(expected);
In a unit test validating the equals(...)
and hashCode()
methods, it’s legitimate to compare an object to itself. This
rule does not raise an issue for isEqualTo
, assertEquals
or hasSameHashCodeAs
when the unit test name contains
(case insensitive): equal
, hash_?code
, object_?method
. For example, in tests with the following names:
test_equals
, testEqual
, test_hashCode
, test_hash_code
, test_object_methods
.
class MyClassTest { @Test void test_equals_and_hash_code() { MyClass obj = new MyClass(); assertThat(obj).isEqualTo(obj); // Compliant assertThat(obj).hasSameHashCodeAs(obj); // Compliant } }