Within Java (disabling assertions in single class)
To enable or disable assertion checking within Java use setClassAssertionStatus in the ClassLoader. For example:
Foo.class.getClassLoader().setClassAssertionStatus(Foo.class.getName(), false);
Within Maven (disabling assertions for all classes)
Since version 2.3.1, Maven Surefire has a separate enableAssertions flag.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>your_version</version>
<configuration>
<enableAssertions>false</enableAssertions>
</configuration>
</plugin>
With JUnit 4 Assume (for single test case)
Ideally, your tests should pass regardless of assertions are enabled or disabled. If one of the tests depends on assertions being disabled, the intended JUnit mechanism is to use an assumption:
import static org.junit.Assume.assumeTrue;
@Test
public foo onlyWithoutAssertions() {
assumeTrue(assertionsDisabled());
// your tricky test comes here, and is only executed in
// environments with assertion checking disabled.
}
public static boolean assertionsDisabled() {
return !Foo.class.desiredAssertionStatus();
}
Note: I typically use this option the other way around: To check that an assert
works as expected, in rare cases I have a test that assumes that assertion checking is enabled.
With JUnit 5 Assume
JUnit 5 assumptions are an extension of the JUnit 4 ones.
Thus, for JUnit 5, the only change to the JUnit 4 code is the import, which now is from jupiter:
import static org.junit.jupiter.api.Assumptions.assumeTrue;