Sub topic 10
Skipping, Tagging, and Conditional Tests
Not every test should run every time. Some tests are slow, some need a database, and some only make sense on Windows. A test can also be broken while someone fixes the code. JUnit 5 gives you three tools for these cases:
- Disabling turns a test off on purpose, with a note saying why.
- Tagging puts a label on a test so you can choose which groups to run.
- Conditions and assumptions let the test decide at run time whether it should run.
This chapter covers all three, uses the Calculator class from earlier chapters, and points out the common mistakes.
Why skip a test at all?
A skipped test is one that JUnit finds but does not execute. The report still lists it, marked as "skipped" instead of passed or failed. That is safer than deleting the test or commenting it out. A commented-out test is easy to forget. A skipped test shows up in every report until someone deals with it.
Here are some common reasons to skip a test:
| Situation | Tool to use |
|---|---|
| The test is broken and a fix is in progress | `@Disabled` |
| The test is slow and you want quick runs while coding | `@Tag` plus a build filter |
| The test only works on one operating system | `@EnabledOnOs` |
| The test needs an environment variable such as a server URL | `@EnabledIfEnvironmentVariable` or an assumption |
| The test needs something you can only check while it runs | `assumeTrue` |
Turning a test off with @Disabled
@Disabled is an annotation that tells JUnit not to run a test. An annotation is a label that starts with @ and gives extra information to a tool. You can put @Disabled on one method or on a whole class.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class CalculatorDisabledTest {
private final Calculator calculator = new Calculator();
@Test
void addWorks() {
assertEquals(5, calculator.add(2, 3));
}
@Test
@Disabled("Waiting for rounding rules from the product team, see ticket CALC-42")
void divideRoundsHalfUp() {
assertEquals(4, calculator.divide(7, 2));
}
}When you run this class, addWorks runs and passes. divideRoundsHalfUp is reported as skipped, and the reason text appears in the report.
Labeling tests with @Tag
@Tag attaches a label to a test or a class. A tag is a short name such as fast, slow, or integration. A tag does nothing by itself. It only matters when you tell the build tool which tags to include or leave out.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
@Tag("calculator")
class CalculatorTaggedTest {
private final Calculator calculator = new Calculator();
@Test
@Tag("fast")
void addIsQuick() {
assertEquals(2, calculator.add(1, 1));
}
@Test
@Tag("slow")
void addManyNumbers() {
int total = 0;
for (int i = 1; i <= 1_000_000; i++) {
total = calculator.add(total, 1);
}
assertEquals(1_000_000, total);
}
}A tag on the class applies to every test inside it. In this example, addIsQuick has the tags calculator and fast.
Tag names cannot contain spaces, commas, parentheses, or the characters &, |, and !. Those characters are reserved for tag expressions, which are covered below.
Choosing tags in Maven
Maven runs tests with the Surefire plugin. You pick tags with the groups and excludedGroups properties.
# Run only tests tagged "fast"
mvn test -Dgroups=fast
# Run everything except tests tagged "slow"
mvn test -DexcludedGroups=slowChoosing tags in Gradle
In Gradle, you set tag filters inside useJUnitPlatform.
tasks.test {
useJUnitPlatform {
includeTags("fast")
excludeTags("slow")
}
}Tag expressions
A tag expression combines tags with & (and), | (or), and ! (not). For example, calculator & !slow means "tagged calculator but not tagged slow".
mvn test -Dgroups="calculator & !slow"Conditional annotations
JUnit has annotations in the package org.junit.jupiter.api.condition that turn a test on or off depending on its surroundings. JUnit checks these conditions before the test starts.
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.condition.OS;
class CalculatorConditionalTest {
private final Calculator calculator = new Calculator();
@Test
@EnabledOnOs(OS.LINUX)
void runsOnlyOnLinux() {
assertEquals(4, calculator.add(2, 2));
}
@Test
@DisabledOnOs(OS.WINDOWS)
void skippedOnWindows() {
assertEquals(3, calculator.divide(9, 3));
}
@Test
@EnabledForJreRange(min = JRE.JAVA_17)
void needsJava17OrNewer() {
assertEquals(0, calculator.add(-1, 1));
}
@Test
@EnabledIfEnvironmentVariable(named = "CI", matches = "true")
void runsOnlyOnTheBuildServer() {
assertEquals(10, calculator.add(5, 5));
}
}CI is an environment variable that many build servers, such as GitHub Actions, set to true. An environment variable is a named value that the operating system passes to programs. On your laptop, CI is usually not set, so the last test is skipped there.
Each "Enabled" annotation has a matching "Disabled" one. There are also @EnabledIfSystemProperty and @DisabledIfSystemProperty for Java system properties.
Assumptions: deciding inside the test
Sometimes you can only learn whether a test should run once it has started. For example, you might need to read a file or a setting first. An assumption is a check that stops the test without failing it when the check is false. JUnit calls this an aborted test, and most reports show it as skipped.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assumptions.assumingThat;
import org.junit.jupiter.api.Test;
class CalculatorAssumptionTest {
private final Calculator calculator = new Calculator();
@Test
void onlyWhenFeatureFlagIsOn() {
String flag = System.getenv("NEW_DIVISION");
assumeTrue("on".equals(flag), "NEW_DIVISION flag is not on");
// Runs only if the assumption held
assertEquals(5, calculator.divide(10, 2));
}
@Test
void partlyConditional() {
// This always runs
assertEquals(4, calculator.add(2, 2));
// This block runs only on the build server
assumingThat("true".equals(System.getenv("CI")),
() -> assertEquals(100, calculator.add(50, 50)));
}
}There are three assumption methods to know:
assumeTrue(condition)aborts the test if the condition is false.assumeFalse(condition)aborts the test if the condition is true.assumingThat(condition, code)runs the code only if the condition is true. The rest of the test runs either way, and the test is never aborted.
How JUnit decides what happens to a test
Common mistakes
- Leaving tests disabled for months. Search your code for
@Disablednow and then, and fix or delete what you find. - Misspelling a tag. If a test is tagged
Slowand you excludeslow, nothing gets excluded, because tags are case-sensitive in practice. Pick one spelling and keep it. - Hiding bugs with assumptions. If an assumption depends on the result of your own code, a bug can turn a failure into a skip.
- A build that skips everything. If every test is skipped on the build server, the build still shows green. Check the skipped count in your reports.
Exercise
You have a test that connects to a real payment server. It should run on the build server, where the variable PAYMENT_URL is set, and be skipped on laptops where it is not set. Which annotation can you put on the test to do this, and what will the report show on a laptop?
Show answer
Use @EnabledIfEnvironmentVariable(named = "PAYMENT_URL", matches = ".+"). The pattern ".+" matches any value that is not empty. On a laptop without the variable, JUnit does not run the test and lists it as skipped.
Exercise
Your Gradle build has includeTags("fast"). A test is tagged @Tag("slow") and also @Disabled. Does the report list it as skipped?
Show answer
No. The tag filter removes the test before JUnit checks @Disabled, so the test does not appear in the report at all.
Exercise
What is the difference between assumeTrue(x) and assumingThat(x, code) when x is false?
Show answer
assumeTrue(x) stops the whole test, and it is reported as aborted (skipped). assumingThat(x, code) skips only the code block and lets the rest of the test run, so the test can still pass or fail.