JUnit assertions are intended to be used in test code, but not in production code.
Using JUnit assertions outside of test scope may be confusing.
Build tools such as Maven might provide JUnit only in test scope, which means JUnit will be missing in the class path, so any invocation of a JUnit assertion in production code (regardless of its outcome) might throw a ClassNotFoundException.
Noncompliant Code Example
package com.myfoo;
import static org.junit.jupiter.api.Assertions.*;
class Foo {
// ...
void doSomething() {
Integer result = getResult();
assertNotNull(result); // Noncompliant -- JUnit method in production code
assertTrue(result > 0); // Noncompliant
assertEquals(42, result); // Noncompliant
}
}
I like the idea, we did not specify the rule further yet, but we plan to add a new set of rules targeting tests for Java in the future, we will definitely come back to your idea when we will start this effort.
I’m also wondering if this could be generalized to any assertion…
I’m also wondering if this could be generalized to any assertion…
JUnit assertions are supposed to be used only in test scope, and this may be true as well for other test frameworks or assertion libraries for languages other than Java.
There is also already a rule that advises against using assert statements for validating parameters
of public methods: Java static code analysis: Asserts should not be used to check the parameters of a public method
However, I don’t think that assertions should be banned from production code in general. Assertions are helpful in documenting the programmer’s assumptions about the inner state of the application.
An assertion that fails indicates a bug, because an assumption was false. The bug remains if you simply remove the assertion.
It is a good practice to review asserts before going live, and replacing them by proper checks where appropriate. I think there may be cases where it is not necessary to remove all assertions.