JUnit 5 assumptions

Assertions verify that expected conditions are met after some executions. In some cases, the assertions may not even be necessary to run. This means that assertions can have assumptions. JUnit 5 provides static methods in the class org.junit.jupiter.api.Assumptions to describe test assumptions. When the assumption is not valid, the org.opentest4j.TestAbortedException is thrown and the test is aborted. There are three groups of static methods in Assumptions, assumeTrue, assumeFalse and assumingThat.

assumeTrue validates the given boolean assumption and abort the test if it’s not true. assumeTrue has six overloaded methods listed below.

  • assumeTrue(boolean assumption)
  • assumeTrue(BooleanSupplier assumptionSupplier)
  • assumeTrue(BooleanSupplier assumptionSupplier, String message)
  • assumeTrue(boolean assumption, Supplier<String> messageSupplier)
  • assumeTrue(boolean assumption, String message)
  • assumeTrue(BooleanSupplier assumptionSupplier, Supplier<String> messageSupplier)

assumeFalse is the opposite of assumeTrue, which also the six similar overloaded methods.

assumingThat executes the given Executable only if the assumption is valid, otherwise it does nothing. assumingThat supports using a boolean value or a BooleanSupplier to provide the assumption.

The code below shows examples of using assumptions. In the test method simpleAssumptions, the line System.out.println("This should never happen.") will not be executed, because the line assumeTrue(false) causes the test execution to abort. In the test method testAssumingThat, there will be only one line This must be true! printed, because the second line does nothing due to invalid assumption.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@DisplayName("Examples of Assumptions")
public class AssumptionsExample {
@Test
@DisplayName("Simple assumptions")
void simpleAssumptions() {
assumeTrue(2 > 1);
assumeFalse(2 < 1);
assumeTrue(false);
System.out.println("This should never happen.");
}
@Test
@DisplayName("assumingThat")
void testAssumingThat() {
assumingThat(2 > 1, () -> System.out.println("This must be true!"));
assumingThat(2 < 1, () -> System.out.println("This should never happen."));
}
}

Check out the book JUnit 5 Cookbook for more new features in JUnit 5.

Comments