Test Assertion In Production Code
ID |
java.avoid_assert_statement |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
reliability, testing |
Description
Reports a call to a JUnit, AssertJ or FestAssert assertion method (assertXxx, fail) made from code that is not test code.
Rationale
Test-assertion methods throw AssertionError, a subclass of Error that production code has no business raising, and pull a test-scoped library into a class that ships to production — a dependency that may not even be on the runtime classpath. A failed check belongs in a domain exception with a message the caller can act on, not in a type meant to fail a build.
public class OrderValidator {
void validateTotals(int expected, int actual) {
org.junit.Assert.assertEquals(expected, actual);
}
}
Remediation
Replace the assertion with an explicit check and a domain-specific exception.
public class OrderValidator {
void validateTotals(int expected, int actual) {
if (expected != actual) {
throw new OrderValidationException("total mismatch: expected " + expected + ", got " + actual);
}
}
}
What is not reported
Java’s own assert keyword is out of scope — it is a language feature the JVM can disable at will, not a test-framework dependency. A file whose package name contains test, assert or junit is also skipped, since that is itself a signal the file is test infrastructure rather than shipped production code.