Simplify Equals Test Assertions
ID |
java.test_assertion_equals_simplify |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
best-practice, junit, testing |
Description
Reports assertTrue(a.equals(b)) calls that should be simplified to assertEquals(b, a), and assertFalse(a.equals(b)) calls that should be simplified to assertNotEquals(b, a).
Rationale
When assertTrue(a.equals(b)) fails, the failure message only says the condition was false, without showing the actual values of a and b. Using assertEquals instead provides a detailed message showing both expected and actual values, making test failures much easier to diagnose.
// Bad - loses value context on failure
assertTrue(result.equals(expected));
assertFalse(actual.equals(forbidden));
// Bad - with message
assertTrue("values should match", a.equals(b));
Remediation
Replace assertTrue(a.equals(b)) with assertEquals(b, a) and assertFalse(a.equals(b)) with assertNotEquals(b, a).
// Good - shows expected and actual on failure
assertEquals(expected, result);
assertNotEquals(forbidden, actual);