Verify test execution control using assumptions in JUnit
Preconditions (2)
✅ Expected Result: The test runs and passes when the assumption is true. The test is skipped (not failed) when the assumption is false.
import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class AssumptionControlTest { @Test void testOnlyOnDevEnvironment() { String env = System.getProperty("env", "prod"); assumeTrue("dev".equals(env), "Test skipped: not in dev environment"); // This assertion runs only if assumption passes assertEquals(4, 2 + 2, "Basic math should work"); } }
This test uses assumeTrue to check if the system property env equals dev. If it does, the test continues and asserts that 2 + 2 equals 4. If not, the test is skipped, not failed.
This shows how assumptions control whether a test runs or is skipped based on conditions, helping avoid false failures when environment conditions are not met.
Now add data-driven testing with 3 different environment values: 'dev', 'test', and 'prod'. The test should only run for 'dev' and skip for others.
Assumptions.assumeTrue() in a JUnit test?Assumptions.assumeTrue(condition); with capital A and method assumeTrue.Assumptions.assumeTrue(System.getProperty("os.name").startsWith("Windows"));
assertEquals(4, 2 + 2);System.getProperty("os.name") does not start with "Windows", so assumeTrue condition is false.@Test
void testFeature() {
Assumptions.assumeTrue(isDatabaseAvailable());
assertTrue(runQuery());
}
boolean isDatabaseAvailable() {
return false;
}Assumptions.assumeTrue is not imported or used incorrectly, assumption may not skip test properly.TEST_ENV equals "prod". Which JUnit 5 code snippet correctly uses assumptions to control test execution?Assumptions.assumeTrue(condition) skips the test if condition is false, so test runs only when TEST_ENV equals "prod".Pass the test and this pattern moves unknown