Assumptions
Assumptions are typically used whenever it does not make sense to continue execution of a given test — for example, if the test depends on something that does not exist in the current runtime environment.
-
When an assumption is valid, the assumption method does not throw an exception, and execution of the test continues as usual.
-
When an assumption is invalid, the assumption method throws an exception of type
org.opentest4j.TestAbortedExceptionto signal that the test should be aborted instead of marked as a failure.
JUnit Jupiter comes with a subset of the assumption methods that JUnit 4 provides and adds a few that lend themselves well to being used with Java 8 lambda expressions and method references.
All JUnit Jupiter assumptions are static methods in the org.junit.jupiter.api.Assumptions class.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assumptions.assumingThat;
import example.util.Calculator;
import org.junit.jupiter.api.Test;
class AssumptionsDemo {
private final Calculator calculator = new Calculator();
@Test
void testOnlyOnCiServer() {
assumeTrue("CI".equals(System.getenv("ENV")));
// remainder of test
}
@Test
void testOnlyOnDeveloperWorkstation() {
assumeTrue("DEV".equals(System.getenv("ENV")),
() -> "Aborting test: not on developer workstation");
// remainder of test
}
@Test
void testInAllEnvironments() {
assumingThat("CI".equals(System.getenv("ENV")),
() -> {
// perform these assertions only on the CI server
assertEquals(2, calculator.divide(4, 2));
});
// perform these assertions in all environments
assertEquals(42, calculator.multiply(6, 7));
}
}
It is also possible to use methods from JUnit 4’s org.junit.Assume class for
assumptions. Specifically, JUnit Jupiter supports JUnit 4’s AssumptionViolatedException
to signal that a test should be aborted instead of marked as a failure.
|