0
0
JUnittesting~5 mins

Custom conditions with @EnabledIf in JUnit

Choose your learning style9 modes available
Introduction

We use @EnabledIf to run tests only when certain conditions are true. This helps save time by skipping tests that don't apply.

Run a test only if a specific system property is set.
Skip tests on certain operating systems like Windows or Mac.
Enable tests only when a database connection is available.
Run tests based on environment variables like 'TEST_ENV=prod'.
Control test execution depending on custom logic in your code.
Syntax
JUnit
@EnabledIf(expression = "${condition}")
void testMethod() {
    // test code
}

The expression is a Spring Expression Language (SpEL) string.

Conditions can check system properties, environment variables, or custom methods.

Examples
This test runs only on Linux machines.
JUnit
@EnabledIf(expression = "${os.name} == 'Linux'")
void testOnlyOnLinux() {
    // test code
}
This test runs only if the system user is 'admin'.
JUnit
@EnabledIf(expression = "${systemProperties['user.name']} == 'admin'")
void testForAdminUser() {
    // test code
}
This test runs only if the custom method isDatabaseAvailable() returns true.
JUnit
@EnabledIf(expression = "@myConditionChecker.isDatabaseAvailable()")
void testIfDatabaseIsUp() {
    // test code
}
Sample Program

This class has two tests. The first runs only if the environment variable TEST_MODE is set to 'true'. The second runs only on Windows OS.

JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;

public class CustomConditionTest {

    @Test
    @EnabledIf(expression = "${env.TEST_MODE} == 'true'", reason = "Runs only if TEST_MODE environment variable is true")
    void testRunsOnlyInTestMode() {
        System.out.println("Test is running because TEST_MODE is true");
    }

    @Test
    @EnabledIf(expression = "${os.name}.toLowerCase().contains('windows')", reason = "Runs only on Windows OS")
    void testRunsOnlyOnWindows() {
        System.out.println("Test is running on Windows OS");
    }
}
OutputSuccess
Important Notes

Make sure the condition expression is valid SpEL syntax.

Use the reason attribute to explain why a test is enabled or disabled.

Environment variables and system properties can be accessed in expressions.

Summary

@EnabledIf lets you run tests only when a condition is true.

Conditions use Spring Expression Language (SpEL) for flexibility.

This helps run tests smartly based on environment or custom logic.