Sometimes tests should run only on certain operating systems. @EnabledOnOs helps run tests only on the OS you want.
0
0
@EnabledOnOs for OS-specific tests in JUnit
Introduction
You want to test a feature that works only on Windows.
You have code that behaves differently on MacOS and want to test it there.
You want to skip tests on Linux because they fail due to OS differences.
You are testing OS-specific file paths or commands.
You want to avoid running tests on unsupported OS to save time.
Syntax
JUnit
@EnabledOnOs(OS.WINDOWS)
void testMethod() {
// test code
}You can specify one or more OS values inside @EnabledOnOs.
This annotation is part of JUnit 5 and helps control test execution based on OS.
Examples
This test runs only on Windows OS.
JUnit
@EnabledOnOs(OS.WINDOWS)
void testWindowsOnly() {
// test code for Windows
}This test runs only on MacOS and Linux.
JUnit
@EnabledOnOs({OS.MAC, OS.LINUX})
void testUnixLike() {
// test code for Mac and Linux
}This test runs only on Linux OS.
JUnit
@EnabledOnOs(OS.LINUX)
void testLinuxOnly() {
// test code for Linux
}Sample Program
This class has two tests. One runs only on Windows, the other runs only on Mac and Linux. When you run the tests on your OS, only the matching tests run.
JUnit
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledOnOs; import org.junit.jupiter.api.condition.OS; public class OsSpecificTest { @Test @EnabledOnOs(OS.WINDOWS) void testRunsOnlyOnWindows() { System.out.println("Running Windows-specific test"); // Imagine some Windows-only logic tested here } @Test @EnabledOnOs({OS.MAC, OS.LINUX}) void testRunsOnMacAndLinux() { System.out.println("Running Mac/Linux-specific test"); // Imagine some Unix-like OS logic tested here } }
OutputSuccess
Important Notes
If you run the sample on Windows, only the Windows test prints its message.
On Mac or Linux, only the Mac/Linux test prints its message.
Tests skipped by @EnabledOnOs are marked as skipped in the test report.
Summary
@EnabledOnOs runs tests only on specified operating systems.
Use it to avoid running tests where they don't apply or would fail.
It helps keep test runs fast and relevant to the environment.