Assumptions help decide if a test should run or skip based on conditions. This stops tests from running when the setup is not right.
0
0
Why assumptions control test execution in JUnit
Introduction
When a test needs a specific environment or data to run.
When a feature is only available on certain platforms or versions.
When external resources like databases or files must be present.
When a test depends on user permissions or settings.
When skipping tests that are not relevant in the current context.
Syntax
JUnit
assumeTrue(condition); assumeFalse(condition); assumeThat(value, matcher);
Use assumeTrue to continue test only if condition is true.
If assumption fails, JUnit skips the test instead of failing it.
Examples
Run test only if OS is Windows.
JUnit
assumeTrue(System.getProperty("os.name").startsWith("Windows"));
Skip test if user is a guest.
JUnit
assumeFalse(user.isGuest());
Run test only if version is 5 or higher.
JUnit
assumeThat(version, org.hamcrest.Matchers.greaterThanOrEqualTo(5));Sample Program
This test class has two tests. The first runs only on Linux. The second skips on Windows. If assumptions fail, tests are skipped, not failed.
JUnit
import static org.junit.jupiter.api.Assumptions.*; import org.junit.jupiter.api.Test; public class AssumptionTest { @Test void testOnlyOnLinux() { assumeTrue(System.getProperty("os.name").startsWith("Linux")); System.out.println("Running test on Linux"); } @Test void testSkippedOnWindows() { assumeFalse(System.getProperty("os.name").startsWith("Windows")); System.out.println("Running test not on Windows"); } }
OutputSuccess
Important Notes
Assumptions help keep test results clean by skipping irrelevant tests.
Skipped tests show as 'skipped' in reports, not as failures.
Use assumptions to check environment, data, or config before running tests.
Summary
Assumptions control if a test runs or skips based on conditions.
They prevent false failures when setup is not right.
Use assumptions to make tests smarter and results clearer.