Introduction
This tutorial will show you how to disable tests based on a condition using JUnit5. In the following examples, I am using annotations from JUnit Jupiter to specify which tests I want to run or not run based on a condition.
Disable test for an operating system
In case you need to run a test on a particular operating system you can use the @EnabledOnOs and @DisabledOnOs annotations. With these annotations, you can disable a test, so it does not run on for example Linux based machines. The annotations accept a single value or you pass multiple operating systems using an array.
|
|
Disable test for a Java version
You can prevent tests from running on a particular Java runtime. To do this you can use the @DisabledOnJre or @EnabledOnJre annotation. The annotations accept a single runtime version or an array of versions as input to enable or disable the test. Having to fill in every Java version can be quite tedious, there is also a @EnabledForJreRange that you can use to specify a range of Java versions.
|
|
Disable test based on system property
You can also disable a test based on a system property. You can use this to only run tests on certain machines that have that system property set. In the following example the tests are disabled or enabled based on a system property using the @EnabledIfSystemProperty and @DisabledIfSystemProperty.
|
|
Disable test based on environment variable
It is also possible to disable tests based on an environment variable. To do this use the @EnabledIfEnvironmentVariable or @DisabledIfEnvironmentVariable. You can use these annotations on a test or container. In the following example, the test is enabled and disabled based on an environment variable.
|
|
Disable or enable tests for native images
Disabling or enabling a test for native images is also possible. You can use these @EnabledIfSystemProperty and @DisabledIfSystemProperty annotations on tests. In the following example, a test is disabled for native images and one is enabled for native images.
|
|
Disable test based on method return value
If you need more control over when a test should be disabled or enabled you can also tell JUnit to run a function to see if a test should run. Both the @EnabledIf and @DisabledIf and accept a function name as input that will be checked if a test should run or not. In the following examples, the conditionForTests function is called to see if a test should run or not.
|
|
Conclusion
In this tutorial, we looked at ways to disable tests based on a condition. With the annotations explained in this tutorial, you can disable or enable a test with just a single line of code. if you want to know more about these annotations please take a look at their official documentation.