How to Use Assumptions in JUnit for Conditional Test Execution
In JUnit, use
Assumptions.assumeTrue() or Assumptions.assumeFalse() to skip tests when conditions are not met. If an assumption fails, the test is aborted and marked as skipped, not failed.Syntax
JUnit provides the Assumptions class with static methods to check conditions before running a test. If the condition is false, the test is skipped.
Assumptions.assumeTrue(condition): Continues test only ifconditionis true.Assumptions.assumeFalse(condition): Continues test only ifconditionis false.Assumptions.assumeTrue(condition, message): Same as above but with a message shown when skipped.
java
import static org.junit.jupiter.api.Assumptions.*; // Example usage inside a test method assumeTrue(System.getProperty("os.name").startsWith("Windows")); // Test continues only if running on Windows
Example
This example shows a test that only runs if the system property env equals dev. Otherwise, the test is skipped.
java
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assumptions.*; public class AssumptionExampleTest { @Test void testOnlyOnDevEnvironment() { assumeTrue("dev".equals(System.getProperty("env")), "Test skipped: not in dev environment"); // Test logic here System.out.println("Running test in dev environment"); // Assertions can go here } }
Output
Running test in dev environment
Common Pitfalls
Common mistakes when using assumptions include:
- Using assumptions for test verification instead of skipping tests. Assumptions should only check preconditions.
- Not importing
Assumptionsstatically, making code verbose. - Confusing failed assumptions with test failures; failed assumptions skip tests, they do not fail them.
Wrong usage example:
assertTrue(condition); // Fails test if false, not skips
Right usage example:
assumeTrue(condition); // Skips test if false
java
import static org.junit.jupiter.api.Assumptions.*; // Wrong: fails test if condition false // assertTrue(condition); // Right: skips test if condition false assumeTrue(condition);
Quick Reference
| Method | Description |
|---|---|
| assumeTrue(condition) | Continues test only if condition is true; skips otherwise |
| assumeFalse(condition) | Continues test only if condition is false; skips otherwise |
| assumeTrue(condition, message) | Same as assumeTrue with skip message |
| assumeFalse(condition, message) | Same as assumeFalse with skip message |
Key Takeaways
Use assumptions to skip tests when preconditions are not met, not to fail tests.
Assumptions like assumeTrue and assumeFalse help conditionally run tests based on environment or state.
Failed assumptions mark tests as skipped, keeping test reports clear and meaningful.
Always import Assumptions statically for cleaner test code.
Avoid mixing assertions and assumptions; assertions verify behavior, assumptions check test conditions.