Introduction
This post explains how to run Junit 5 test only if they meet a specific condition. This is useful for a test you want only to run on a certain OS, other criteria like time of day for example.
Run test only on certain Operating systems
There are test cases you only want to run a specific operating system (OS). To enable or disable a test for a particular OS, you can use the @EnabledOnOs and @DisabledOnOs, respectively. These annotations will let you disable/enable specific tests based on the OS parameter you passed as a parameter.
In the following example, you can see various ways of using this annotation on test cases.
|
|
Run test only on certain Java versions
It is also possible to enable or disable a test case based on the Java version that is executing the test. To do so, you can use the @EnabledOnJre or @DisabledOnJre annotation. These annotations accept a single Java version or an array of versions.
There are also two annotations that let you set a range for the Java versions, for example, from Java 8 to version 17. In the following example, you can see how we use these annotations:
|
|
Run tests based on an environment variable
Disabling a test based on an environment variable works the same as we would do with a system variable. To do so, use the
@EnabledIfEnvironmentVariable and the @DisabledIfEnvironmentVariable. These annotations take as a parameter the name of the environment variable and
an expression that will be matched against the environment variable.
In the following example, you can see how we use this annotation:
|
|
Run tests based on a custom method call
If the built-in annotations don't cover your use case, you can also use a method that returns a boolean. To enable/disable a test based on a method's return value, use the @EnabledIf or @DisabledIf annotation. The annotation takes as a parameter the name of the method you want to use.
In the following example, you can see how we use the method to enable or disable a test from running.
|
|
Conclusion
In this article, we looked at how we can disable and enable threads based on different kinds of conditions. We used the operating system, Java Version, Environment variable, and a custom method to determine if a test should run or not.
Further reading
More about testing in Java: