Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 29 ยท JUnit core

Conditions, Tags and Selecting Tests

Run the right JUnit 6 tests in the right place: @EnabledOnOs, @EnabledIf, assumptions, @Tag filtering, @RepeatedTest, @Timeout and selecting tests with the Launcher.

A project test suite is not one thing. Some tests take milliseconds and should run on every save; others start a database and run only in CI. Some make sense only on Linux, or only when a secret is set, or only on a recent Java. JUnit gives you three tools for that: conditions (a test switches itself off), tags (you label tests and choose labels at run time), and selectors (you name exactly which classes or methods to run).

All three are runnable on this site, because they are part of the real JUnit API. Only the build tool filters at the end of the lesson (Maven and Gradle syntax) are shown read-only. The lesson builds on Lifecycle, Nested Tests and Display Names.

Three ways to choose tests

Conditions A test skips itself when its environment is wrong.
Tags Label tests, then include or exclude labels.
Selectors Name the class, method or package to run.
1 / 2

Conditions: tests that skip themselves

Jupiter ships a family of annotations that evaluate before the test method runs. If the condition is false, the test is reported as skipped with a reason. The most useful ones:

Annotation Skips (or runs) the test...
@EnabledOnOs(OS.LINUX) / @DisabledOnOs(OS.WINDOWS) depending on the operating system
@EnabledOnJre(JRE.JAVA_21), @EnabledForJreRange(min = JRE.JAVA_21) depending on the Java version
@EnabledIfSystemProperty(named = "ci", matches = "true") when a system property matches a regex
@EnabledIfEnvironmentVariable(named = "API_KEY", matches = ".+") when an environment variable matches
@EnabledIf("methodName") / @DisabledIf("methodName") when a boolean method of your choosing returns true
@Disabled("reason") never (unconditionally)

@EnabledIf takes the name of a method that returns boolean (in the test class itself, or a static one in another class), so you can express any rule you like: "the file exists", "the port is free", "it is a weekday". For a static method in another class, use a fully qualified name such as com.shop.Checks#redisIsUp.

Conditions are for environment, not for hiding broken tests. If a test fails because the code is wrong, fix the code; do not add a condition that happens to be false.

Assumptions: deciding inside the test

Sometimes you only know whether a test is meaningful after some setup. Assumptions.assumeTrue(condition) (and assumeFalse, assumingThat) lets the body bail out. A failed assumption does not fail the test; it aborts it, and reports call it "aborted" instead of "failed". Use assumptions for "this test does not apply here", never to avoid fixing something.

The example below mixes a few conditions and two assumptions. Its output on our Linux-based runner is deterministic.

Java Conditions and assumptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the summary: some tests passed, some were skipped by annotations (the body never started), and one was aborted by an assumption (the body started and stopped at the assumption line). Both outcomes stay out of the failure count, so a build stays green, but they show up in reports so you can see how much of the suite actually ran.

Tags: label tests, choose labels later

@Tag("name") attaches a label to a class or a method. Tags are free-form strings (letters, digits and a few symbols; no spaces or commas). Common labels are fast, slow, integration, db or smoke. You then include or exclude tags when you run the suite.

Java
@Tag("fast")
class PriceCalculatorTest { ... }

@Tag("integration")
@Tag("db")
class OrderRepositoryTest { ... }

The decision happens at launch time, so the same compiled tests serve both your quick local loop (fast only) and your CI pipeline (everything). In a real build you pass the tags to Maven or Gradle (shown later). Underneath, the build tool builds a LauncherDiscoveryRequest with a TagFilter. We can build the same request by hand, which is what the next example does: one class of tests, run three times with different filters.

Java Choosing tests by tag with the Launcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first run executes all four tests. Including fast leaves two, because an untagged test has no tags and an include filter only matches tests that carry one of the listed tags. Excluding slow drops only the database test and keeps the untagged one. That asymmetry matters: when you want "everything except slow", use an exclude, not an include.

Tag expressions are more powerful than lists. In Maven and Gradle you can write fast & !flaky, integration | smoke or (fast | smoke) & !db.

Custom composed annotations

If you type @Tag("fast") in two hundred places, a typo creates a ghost tag nobody filters on. Define your own annotation once and reuse it:

Java
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Tag("integration")
@Test
public @interface IntegrationTest { }

A method annotated with @IntegrationTest is both a test and tagged integration. This works because Jupiter annotations are meta-annotations: they can be placed on your own annotations.

Selectors: naming what to run

Tags choose by label; selectors choose by identity. The DiscoverySelectors class offers the building blocks the Launcher understands:

  • selectClass(MyTest.class): all tests of one class.
  • selectMethod(MyTest.class, "parsesAPrice"): a single method. Your IDE does this when you click the run arrow next to one test.
  • selectPackage("com.shop.checkout"): every test class under a package.
  • selectUniqueId(...): one exact test, including a parameterized invocation.

You can combine selectors with filters, such as a class selector plus includeTags("fast"), as the previous example did.

Repeating, timing and limiting tests

Two more annotations help with how a test runs.

@RepeatedTest(n) runs the same test n times, each shown as its own result. A parameter of type RepetitionInfo tells you which repetition you are in. It is mainly useful for chasing flakiness, or checking code that uses randomness with different seeds.

@Timeout fails a test that takes too long, with a message such as ... timed out after 100 milliseconds. The limit applies to the whole test method, including @BeforeEach calls, and on a busy build server a tight limit causes false alarms. The default unit is seconds.

Java @RepeatedTest and @Timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The three repetitions pass individually, finishesInTime passes, and tooSlow fails with a timeout message. By default @Timeout interrupts the test thread but runs the test on that same thread, so thread-local state (such as transactions) still works. That is different from the preemptive timeout assertion you will meet in Testing Exceptions, Timeouts and Async Code.

Filters in Maven and Gradle (read-only)

On a real project you do not write launcher code; you pass the same ideas to the build tool. The Maven Surefire plugin takes tag expressions and test names:

Terminal
mvn test -Dgroups="fast"            # only tests tagged fast
mvn test -DexcludedGroups="slow"    # everything except slow
mvn test -Dtest=PriceCalculatorTest # one class
mvn test -Dtest=PriceCalculatorTest#parsesAPrice

Gradle configures the same through useJUnitPlatform { includeTags("fast") } in the test task and a --tests command-line filter. The full picture, including Failsafe for integration tests, is in Running Tests with Maven and Gradle.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test has @EnabledOnOs(OS.WINDOWS) and runs on Linux. How is it reported?

    Conditional annotations are evaluated before the method. When the condition is false the test is skipped with a reason.
  2. 2. What is the difference between a skipped and an aborted test?

    Conditions skip tests before they start. Assumptions run inside the body, and a failed assumption aborts the test. Neither counts as a failure.
  3. 3. You run only tests included with the tag fast. Does an untagged test run?

    Untagged tests have no tag to match, so an include filter leaves them out. Use an exclude filter when you want everything except a tag.
  4. 4. Which selector would you use to run exactly one test method?

    selectMethod(MyTest.class, "name") targets a single method; IDEs use it when you run one test.
  5. 5. Why does a very short @Timeout often cause problems in CI?

    Timing depends on load. Use generous limits so a slow machine does not turn a correct test red.

Summary

  • Condition annotations (@EnabledOnOs, @EnabledIf, @EnabledIfEnvironmentVariable, and friends) skip a test before it starts; assumptions abort it from inside.
  • @Tag labels tests so you can include or exclude them at launch time; an include filter does not match untagged tests.
  • Compose your own annotation when the same tag is used widely, so typos cannot hide tests.
  • Selectors (selectClass, selectMethod, selectPackage) pick tests by identity and combine with tag filters in a LauncherDiscoveryRequest.
  • @RepeatedTest repeats a test, and @Timeout fails slow ones; keep limits generous.
  • Maven and Gradle pass the same ideas through -Dgroups, -DexcludedGroups, -Dtest and includeTags.

Next: Parameterized and Dynamic Tests, where one test method runs against many inputs.