We use assumeTrue and assumeFalse to skip tests when certain conditions are not met. This helps avoid running tests that don't make sense in the current situation.
0
0
assumeTrue and assumeFalse in JUnit
Introduction
When a test should only run if a file exists on the system.
When a test depends on a specific environment variable being set.
When a test requires a certain version of Java to run.
When a test needs a network connection and should skip if offline.
When a test only applies to a specific operating system.
Syntax
JUnit
Assumptions.assumeTrue(condition); Assumptions.assumeFalse(condition);
condition is a boolean expression.
If the assumption fails, the test is skipped, not failed.
Examples
Runs the test only if
userIsLoggedIn is true.JUnit
Assumptions.assumeTrue(userIsLoggedIn);
Skips the test if
isDatabaseDown is true.JUnit
Assumptions.assumeFalse(isDatabaseDown);
Sample Program
The first test runs because 5 > 3 is true.
The second test runs because 2 > 3 is false, so assumeFalse passes.
The third test is skipped because 1 > 3 is false, so assumeTrue fails and the test does not run.
JUnit
import static org.junit.jupiter.api.Assumptions.*; import org.junit.jupiter.api.Test; public class SampleTest { @Test void testOnlyIfTrue() { assumeTrue(5 > 3); System.out.println("Test ran because assumption was true."); } @Test void testSkippedIfFalse() { assumeFalse(2 > 3); System.out.println("Test ran because assumption was false."); } @Test void testSkipped() { assumeTrue(1 > 3); System.out.println("This line will not print because assumption failed."); } }
OutputSuccess
Important Notes
Assumptions help keep test results clean by skipping irrelevant tests instead of failing them.
Use assumptions to check environment or setup before running a test.
Summary
assumeTrue runs the test only if the condition is true.
assumeFalse runs the test only if the condition is false.
Failed assumptions skip tests instead of failing them.