0
0
JUnittesting~15 mins

@EnabledOnOs for OS-specific tests in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify feature behavior only on Windows OS
Preconditions (2)
Step 1: Create a test method annotated with @EnabledOnOs(OS.WINDOWS)
Step 2: Inside the test method, perform a simple assertion like checking a string equals 'Windows'
Step 3: Run the test on Windows OS and observe it runs
Step 4: Run the test on a non-Windows OS and observe it is skipped
✅ Expected Result: The test runs and passes only on Windows OS. On other OS, the test is skipped and does not fail.
Automation Requirements - JUnit 5
Assertions Needed:
Assert that a string equals 'Windows' inside the test method
Best Practices:
Use @EnabledOnOs annotation to restrict test execution by OS
Keep test methods simple and focused
Use descriptive test method names
Avoid hardcoding OS checks inside test logic
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class OperatingSystemTest {

    @Test
    @EnabledOnOs(OS.WINDOWS)
    void testRunsOnlyOnWindows() {
        String osName = "Windows";
        assertEquals("Windows", osName, "Test should run only on Windows OS");
    }
}

The test class OperatingSystemTest contains one test method testRunsOnlyOnWindows.

This method is annotated with @EnabledOnOs(OS.WINDOWS), which means JUnit will run this test only if the OS is Windows.

Inside the test, we assert that the string osName equals "Windows". This simple assertion confirms the test logic.

If you run this test on Windows, it will execute and pass. On other OS like Linux or Mac, JUnit will skip this test without failing it.

This approach keeps OS-specific tests clean and avoids manual OS checks inside the test code.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not importing the correct JUnit 5 annotations', 'why_bad': "The test will not compile or the annotations won't work as expected", 'correct_approach': 'Import org.junit.jupiter.api.condition.EnabledOnOs and org.junit.jupiter.api.condition.OS'}
Using @EnabledOnOs on a test method but running on unsupported OS expecting it to fail
Hardcoding OS checks inside test logic instead of using @EnabledOnOs
Bonus Challenge

Now add tests that run only on Linux and Mac OS using @EnabledOnOs with multiple OS values

Show Hint