Simplify Operator Test Assertions
ID |
java.test_assertion_ops_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 == b), assertFalse(a != b), and similar patterns that use relational or equality operators (==, !=, <, ⇐, >, >=) inside boolean assertions. These patterns lose value context on failure and should use dedicated assertion methods.
Rationale
When assertTrue(a == b) fails, the failure message only states that the condition was false, without revealing the actual values of a and b. Using assertEquals(b, a) instead shows both expected and actual values, significantly reducing the time needed to diagnose test failures. The same applies to relational operators where dedicated comparator-based assertions can provide richer context.
// Bad - loses value context on failure
assertTrue(count == 5);
assertFalse(index != 0);
assertTrue(score > threshold);
assertTrue(size >= minSize);
This rule does not flag null comparisons (x == null), which are handled by the test_assertion_null_simplify rule, or .equals() calls, which are handled by the test_assertion_equals_simplify rule.
|
Remediation
Replace boolean assertions containing comparison operators with dedicated assertion methods.
// Good - shows expected and actual on failure
assertEquals(5, count);
assertEquals(0, index);
assertTrue("score should exceed threshold: " + threshold, score > threshold);