0
0
JUnittesting~15 mins

Why assumptions control test execution in JUnit - Automation Benefits in Action

Choose your learning style9 modes available
Verify test execution control using assumptions in JUnit
Preconditions (2)
Step 1: Write a test method that uses an assumption to check if a system property 'env' equals 'dev'
Step 2: If the assumption is true, proceed to assert that 2 + 2 equals 4
Step 3: If the assumption is false, the test should be skipped and not fail
Step 4: Run the test with system property 'env' set to 'dev' and verify the test passes
Step 5: Run the test with system property 'env' set to 'prod' and verify the test is skipped
✅ Expected Result: The test runs and passes when the assumption is true. The test is skipped (not failed) when the assumption is false.
Automation Requirements - JUnit 5
Assertions Needed:
Assert that 2 + 2 equals 4 when assumption passes
Verify test is skipped when assumption fails
Best Practices:
Use org.junit.jupiter.api.Assumptions for assumptions
Use @Test annotation for test methods
Avoid hardcoding values; use system properties for assumptions
Keep tests independent and clear
Automated Solution
JUnit
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.

Common Mistakes - 3 Pitfalls
Using assertions instead of assumptions to check environment
Hardcoding environment values inside the test
Not providing a message in assumption leading to unclear test reports
Bonus Challenge

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.

Show Hint