Self-Comparing Assertion
ID |
java.assertions_compare_object_itself |
Severity |
critical |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Reliability |
Language |
Java |
Tags |
reliability, suspicious-comparison, testing |
Description
Reports a JUnit, AssertJ or FestAssert assertion whose two compared expressions are the very same variable, field or field-access chain, such as assertThat(shipment).isEqualTo(shipment) or assertEquals(total, total).
Rationale
An assertion comparing an expression to itself always evaluates to the same result and can never catch a regression: it proves nothing about the code under test. It is almost always the result of a copy-paste mistake where the second occurrence of a variable was meant to be a different one.
@Test
void shipmentMatchesExpected() {
Shipment shipment = repository.find("SHIP-1");
assertThat(shipment).isEqualTo(shipment); // always true, catches nothing
}
Remediation
Compare the actual value against an independently computed expected value.
@Test
void shipmentMatchesExpected() {
Shipment shipment = repository.find("SHIP-1");
Shipment expected = new Shipment("SHIP-1", Status.DELIVERED);
assertThat(shipment).isEqualTo(expected);
}
What is not reported
Only expressions guaranteed to evaluate the same way twice are compared: a bare variable, field or field-access chain. A method call, object or array allocation, lambda or method reference is never treated as self-compared, because two syntactically identical occurrences of one of those can produce different values, so nothing is reported for assertThat(fetchShipment()).isEqualTo(fetchShipment()).
A fluent AssertJ chain is only followed through context-setting calls such as as(…) or withFailMessage(…); any other call between the entry point and the terminal comparison (for example extracting(…)) may have changed the value under test, so the chain is left unreported rather than guessed at.
Inside a unit test whose name documents it as an equals()/hashCode() check (containing equal, hash_code or object_method, case-insensitive), comparing an object to itself via isEqualTo, assertEquals or hasSameHashCodeAs is a legitimate way to exercise those methods and is not reported.