Assumptions are similar to assertions, except that assumptions must hold true or the test will be aborted. In contrast, when an assertion fails, the test is considered to have failed. JUnit Assumptions helps us in skipping a test for some specific scenario. Sometimes our test cases are dependent on the inputs, operating systems or any third party data. If our test is not written for some specific inputs, then we can use assumptions to skip our test method.

An assumption is a static method of the org.junit.jupiter.api.Assumptions class. To appreciate the value of assumptions, all you need is a simple example. Suppose you want to run a particular unit test only on Monday:

@Test
@DisplayName("This test is only run on Mondays")
public void testAdd_OnlyOnMonday() {
  LocalDateTime ldt = LocalDateTime.now();
  assumeTrue(ldt.getDayOfWeek().getValue() == 1);
  // Rest of the test executed only if assumption is valid
}

We can use assumeTrue() to skip the test if the above condition evaluates to false.

We can use assumeFalse() to validate that the condition is returning false. Let’s say we have a test method that we don’t want to run with Windows operating system:

@Test
public static void skipWindowsOs() {
    Assume.assumeFalse(OperationSystemHelper.isWindows());
}

assumingThat()

This method executes the supplied Executable if the assumption is valid. If the assumption is invalid, this method does nothing. We can use this for logging or notifications when our assumptions are valid. Example:

@Test
	void testInAllEnvironments() {
		assumingThat("Redis".equals(System.getenv("ENV")),
			() -> {
				// perform these assertions only on the Redis server
				assertEquals(4, checkNumberOfCPU());
			});

		// perform these assertions in all environments
		assertEquals(2048, checkFreeMemory());
}
FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials