Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 119 ยท Testing

Test Lifecycle and Organization

Control the JUnit 6 test lifecycle with @BeforeEach and @BeforeAll, group tests with @Nested and @DisplayName, and skip or filter them with @Disabled, @Tag and assumptions.

A handful of tests fits in one flat class. A real project has hundreds or thousands, and they need structure: shared setup that runs before each test, expensive resources created only once, groups that read like a specification, and a way to run only the fast tests on every save and the slow ones before a merge.

JUnit Jupiter gives you all of that through a few annotations. In this lesson you will see exactly when each lifecycle method runs (and why JUnit creates a new test object for every test), group tests with @Nested and @DisplayName, switch tests off with @Disabled, conditions and assumptions, and select tests with @Tag. It builds on Unit Testing with JUnit 6, including the small runTests(...) helper at the bottom of each example, which stands in for Maven, Gradle or your IDE.

The lifecycle of a test class

For every @Test method, JUnit does the same dance:

  1. Create a new instance of the test class (call its constructor).
  2. Run every @BeforeEach method.
  3. Run the test method.
  4. Run every @AfterEach method, even if the test failed.

Around the whole class, @BeforeAll runs once before the first test and @AfterAll once after the last. Because there is no single instance that lives for the whole class, those two methods must be static by default.

The example prints a line from each stage, plus an identity number for the test object, so you can see the order and the fresh instance per test.

Java Watching the lifecycle

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.

Two things to notice in the output. Each test gets its own instance (#1, #2), so the pear that firstTest added is gone by the time secondTest runs: it sees only [apple]. And @AfterEach runs right after each test, before its [PASS] line is printed, because JUnit reports a test as finished only after its cleanup.

That fresh instance is a deliberate design choice. It means tests cannot leak state into each other through fields, so they pass or fail on their own, in any order. Static fields are the exception: they are shared by every test in the JVM, so keep mutable state out of them (the counter above is static on purpose, to count instances).

What goes where

Annotation Runs Typical use
@BeforeEach before every test build the object under test, fresh test data
@AfterEach after every test, pass or fail delete temp files, reset a clock or a global setting
@BeforeAll once per class, before any test (static) start an expensive shared resource: an in-memory database, a server
@AfterAll once per class, after all tests (static) stop that resource

A few rules:

  • You can have several methods with the same annotation, but their order relative to each other is not guaranteed. If order matters, use one method.
  • Lifecycle methods are inherited. A superclass's @BeforeEach runs before the subclass's, and its @AfterEach runs after, so base test classes can provide shared setup.
  • If @BeforeEach throws, the test is reported as failed and the test body does not run, but @AfterEach still does.
  • Prefer a plain helper method (newCartWithTwoItems()) over @BeforeEach when only some tests need the setup. Setup that every reader has to scroll up to find makes tests harder to understand.

JUnit 4 called these @Before, @After, @BeforeClass and @AfterClass. You will still meet them in older code; the Jupiter names are the ones to use.

Changing the instance lifecycle with @TestInstance

Sometimes one object per class is genuinely useful: for example, when @BeforeAll should set up an instance field, or when the test class is written in Kotlin, where static is awkward. Annotate the class with @TestInstance(TestInstance.Lifecycle.PER_CLASS) and JUnit creates one instance for all its tests. @BeforeAll and @AfterAll can then be ordinary instance methods.

The price is that fields are now shared, so tests can affect each other again. The next example runs the same two tests under both lifecycles. Both tests in each class assert that their counter field is 1.

Java PER_METHOD versus PER_CLASS

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.

In PerMethodTest both tests pass. In PerClassTest, whichever test runs second fails with expected: <1> but was: <2>, because it sees the first test's increment. If you choose PER_CLASS, reset mutable fields in @BeforeEach. A project can switch the default for every class with junit.jupiter.testinstance.lifecycle.default = per_class in src/test/resources/junit-platform.properties, but most teams keep the safer default.

Readable names with @DisplayName

Method names cannot contain spaces or punctuation. @DisplayName gives a test or a class any text you like, including spaces and symbols, and IDEs and reports show it instead of the method name:

Java
@Test
@DisplayName("rejects a withdrawal larger than the balance")
void rejectsOverdraft() { ... }

If you prefer to write names like rejects_a_withdrawal_larger_than_the_balance(), put @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) on the class and JUnit turns the underscores into spaces for you. DisplayNameGenerator.IndicativeSentences goes further and joins the class and method names into one sentence. Display names only change what is shown; selecting and filtering tests still uses the real class and method names.

Grouping tests with @Nested

A @Nested class is a non-static inner class inside a test class. It groups tests that share a situation, and it inherits the outer class's setup: for a test in a nested class, the outer @BeforeEach runs first, then the inner one. Each level adds one more piece of context, so the test tree reads like a specification.

Java A specification with @Nested and @DisplayName

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 printed tree is the documentation: "An account / after a deposit of 100 / and a withdrawal of everything / refuses to go below zero". Rules for nested classes:

  • They must be inner classes (no static). A static nested class is just a separate test class with no access to the outer setup.
  • Each test still gets fresh objects: JUnit creates the outer instance and then the inner one for every test.
  • Nest one or two levels deep. Beyond that, the setup chain becomes hard to follow.

Turning tests off: @Disabled and conditions

@Disabled("reason") on a method or class skips it. Always give a reason, ideally with a ticket number, because a disabled test is a debt that someone has to pay back. Reports list it as skipped, so it stays visible.

Conditional annotations skip tests based on the environment:

Annotation Runs the test only when...
@EnabledOnOs(OS.LINUX) / @DisabledOnOs(OS.WINDOWS) the operating system matches / does not match
@EnabledOnJre(JRE.JAVA_25) / @EnabledForJreRange(min = JRE.JAVA_21) the Java version matches
@EnabledIfSystemProperty(named = "env", matches = "ci") a system property matches a regex
@EnabledIfEnvironmentVariable(named = "DB_URL", matches = ".+") an environment variable matches
@EnabledIf("methodName") / @DisabledIf(...) a boolean method you write returns true

Assumptions: aborting a test from the inside

An assumption is a precondition checked while the test runs. If assumeTrue(condition) sees false, JUnit stops the test and reports it as aborted: not passed, not failed. Use assumptions when a test only makes sense in some environments and the check needs code, such as "is a network port free?".

assumingThat(condition, executable) is the gentler version: it runs the given block only when the condition holds, and the rest of the test always runs.

Java Disabled, conditional and aborted tests

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.

Our server runs Linux and Java 25, so windowsOnly is skipped with the reason Disabled on operating system: Linux, needsJava21OrNewer passes, flakyTest is skipped with its reason, and onlyOnTheCiServer is aborted with Assumption failed: BUILD_ENV is not ci. The difference between skipped and aborted: skipped tests are decided before they start, aborted tests start and then bail out.

Don't use assumptions to hide real failures ("assume the service is up"). A test that silently aborts on every machine is worse than no test, because it looks healthy in green dashboards.

Tags and filtering

@Tag("slow") labels a test or a class. Tags do nothing on their own; build tools use them to select tests. A common setup runs fast tests on every commit and slow or integration tests in a later CI stage.

Maven Surefire and Gradle both accept tag expressions with & (and), | (or) and ! (not):

Terminal
mvn test -Dgroups="fast"
mvn test -Dgroups="database & !slow"
mvn test -DexcludedGroups="slow"
Kotlin
tasks.test {
    useJUnitPlatform {
        includeTags("fast")
        excludeTags("slow")
    }
}

Under the hood, these settings become a tag filter on the launcher's discovery request. The example builds one by hand, so you can see the same class filtered three ways.

Java Selecting tests by tag

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.

fast selects two tests, fast & !parsing only formatsTotals, and slow | database only the export test. The untagged test runs only when no include filter is set. Keep the set of tag names short and documented (for example fast, slow, integration, contract); a free-for-all of tags quickly becomes meaningless.

Ordering, timeouts and injected parameters

Order. JUnit's default method order is deterministic but intentionally not obvious, which keeps you from relying on it. For the rare test class that walks through steps (an end-to-end scenario), you can choose an order:

Java
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CheckoutFlowTest {
    @Test @Order(1) void addsItemToCart() { ... }
    @Test @Order(2) void paysForCart() { ... }
}

Other orderers are MethodOrderer.MethodName, MethodOrderer.DisplayName and MethodOrderer.Random (handy for flushing out hidden dependencies between tests). @TestClassOrder does the same for nested classes. For ordinary unit tests, needing an order is a smell: each test should arrange its own state.

Timeouts. @Timeout(2) fails a test (or every test in a class) that runs longer than two seconds; the unit defaults to seconds and can be changed with unit = TimeUnit.MILLISECONDS. Unlike assertTimeout, it also covers lifecycle methods. It is a safety net against hanging tests, not a performance test.

Injected parameters. Test and lifecycle methods may declare parameters that JUnit fills in. TestInfo gives the current display name and tags, TestReporter publishes extra key-value data to reports, and RepetitionInfo belongs to repeated tests (next lesson). Extensions such as Mockito's add more.

Java
@BeforeEach
void logStart(TestInfo info) {
    System.out.println("Starting " + info.getDisplayName() + " " + info.getTags());
}

Organizing the test source tree

Good structure outside the class matters as much as inside it:

  • Mirror the main package layout. com.shop.cart.Cart is tested by com.shop.cart.CartTest in src/test/java. Tools and colleagues find tests instantly.
  • One test class per production class is a good default, and @Nested classes split it by method or scenario. Very large classes can be split into CartPricingTest and CartCheckoutTest.
  • Put shared test helpers in the test tree (src/test/java/.../testsupport), never in production code. Builders like aBook().withTitle("Dune").build() keep arrange sections short.
  • Keep test resources (sample JSON files, SQL scripts) in src/test/resources, loaded from the classpath.
  • Name integration tests distinctly, for example *IT, so build tools can run them in a separate phase. Integration Testing shows the setup.

Test suites with @Suite

Tags select tests from the build file. A suite selects them from code: a class that says "run these classes, or this package, but only the tagged ones". Suites are useful when an IDE or a CI job should be able to run one named group with a single click (a "smoke test" suite, a "database tests" suite) without anyone remembering command-line flags.

Suites come from a separate artifact, junit-platform-suite, which adds the @Suite annotation and its companions (the version is managed by the JUnit BOM, like the other JUnit modules):

XML
<dependency>
  <groupId>org.junit.platform</groupId>
  <artifactId>junit-platform-suite</artifactId>
  <scope>test</scope>
</dependency>

A suite is an empty class whose annotations are the selection:

Java
import org.junit.platform.suite.api.*;

@Suite
@SuiteDisplayName("Smoke tests")
@SelectPackages("com.example.shop")                   // every test class in this package and below
@IncludeTags("smoke")                                 // ...but only tests tagged smoke
class SmokeSuite {
}

@Suite
@SelectClasses({ OrderServiceTest.class, PaymentServiceTest.class })   // exactly these classes
@ExcludeTags("slow")
class CheckoutSuite {
}

@Suite
@SelectPackages({ "com.example.shop.repository", "com.example.shop.web" })
@IncludeClassNamePatterns(".*IntegrationTest")        // regular expressions over the class name
class IntegrationSuite {
}

The annotations fall into three groups:

Group Annotations
Select what to look at @SelectPackages, @SelectClasses, @SelectMethod, @SelectClasspathResource, @SelectDirectories
Filter the selection @IncludeTags, @ExcludeTags, @IncludePackages, @ExcludePackages, @IncludeClassNamePatterns, @ExcludeClassNamePatterns, @IncludeEngines, @ExcludeEngines
Describe and configure @SuiteDisplayName, @ConfigurationParameter (passes a configuration parameter, such as parallel execution settings, to the tests in the suite)

Some practical points:

  • A suite class has no test methods; the suite engine discovers it and runs the selected tests as its children. In a report they appear nested under the suite's name.
  • Surefire's default includes are **/Test*.java, **/*Test.java, **/*Tests.java and **/*TestCase.java. A class called SmokeSuite matches none of them, so either name it SmokeSuiteTest, or add <include>**/*Suite.java</include> to the Surefire configuration. If you do the latter, normal test classes still run on their own as well, so the same test can run twice in one build (once alone, once inside a suite). Many teams therefore use suites only for IDE and local runs, and use tags and Maven profiles in CI.
  • A suite should select with tags or packages, not by listing dozens of classes: a forgotten new class silently drops out of a @SelectClasses list.

Under the hood a suite is a discovery request like the one the tag example built by hand: selectors plus filters, passed to the launcher. The next program runs three "suites" programmatically, with the same selectors and filters as the annotations above (@SelectClasses, @IncludeClassNamePatterns, @IncludeTags) so you can see exactly which tests each one picks:

Java What a suite selects (selectors and filters)

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 real @Suite annotations are not available on this page's runner (only the launcher is), so the example builds the requests by hand. The mapping is direct: @SelectClasses becomes selectClass(...) selectors, @IncludeTags becomes TagFilter.includeTags(...), and @IncludeClassNamePatterns becomes ClassNameFilter.includeClassNamePatterns(...).

Measuring coverage with JaCoCo

Tests prove that some behavior works. Code coverage tells you which code your tests ran at all, so it is good at one thing: finding code no test touches. JaCoCo is the standard coverage tool for Java. It attaches a Java agent to the test JVM, records which instructions run, and writes a report.

Maven setup

XML
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.14</version>        <!-- use a release that supports your JDK's class-file version -->
  <executions>
    <execution>
      <goals><goal>prepare-agent</goal></goals>         <!-- adds -javaagent to Surefire -->
    </execution>
    <execution>
      <id>report</id>
      <phase>test</phase>
      <goals><goal>report</goal></goals>                <!-- target/site/jacoco/index.html -->
    </execution>
    <execution>
      <id>check</id>
      <phase>verify</phase>
      <goals><goal>check</goal></goals>                 <!-- fails the build below a threshold -->
      <configuration>
        <rules>
          <rule>
            <element>BUNDLE</element>
            <limits>
              <limit>
                <counter>LINE</counter>
                <value>COVEREDRATIO</value>
                <minimum>0.80</minimum>
              </limit>
              <limit>
                <counter>BRANCH</counter>
                <value>COVEREDRATIO</value>
                <minimum>0.70</minimum>
              </limit>
            </limits>
          </rule>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

mvn verify runs the tests with the agent, writes target/jacoco.exec (the raw data), turns it into an HTML, XML and CSV report in target/site/jacoco, and fails if a limit is missed. (Gradle users apply the jacoco plugin; jacocoTestReport makes the report and jacocoTestCoverageVerification enforces rules.) Two common problems: a JaCoCo version too old for your JDK reports "Unsupported class file major version", and a <argLine> property in Surefire's configuration can overwrite the agent unless it includes @{argLine}.

You can leave out generated code, such as mappers, configuration classes or Lombok output, with <excludes> in the plugin's configuration (<exclude>**/config/**</exclude>).

Reading the report

The HTML report goes from the whole project, to packages, to classes, to source with colored lines. The columns are counters, and they measure different things:

Counter Counts
Instructions Java bytecode instructions executed (JaCoCo's basic unit; works without source)
Branches each outcome of every if, switch and conditional: an if has two
Lines source lines with at least one executed instruction
Complexity and Methods how many methods ran, and how many independent paths remain untested
Classes classes with at least one executed method

In the source view a line is green when everything ran, yellow when a branch has an outcome that never happened (the little diamond says "1 of 2 branches missed"), and red when it never ran. Yellow lines are the valuable ones: they mark conditions that your tests only ever exercised one way.

That is why line coverage can reach 100% with half the logic untested. The last example makes it visible. It is not JaCoCo (an agent that rewrites bytecode can't run here); it is a hand-instrumented method with a tiny recorder that tracks lines and branch outcomes, which is conceptually what JaCoCo does automatically.

Java 100% line coverage, 50% branch coverage

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 report line is the trap: every line has run (100%), but the else outcome of the if never happened, so only half of the branch outcomes are covered. In a real report that line is yellow, not green. The "never executed lines" at the bottom is what a red line in the report looks like.

Using coverage sensibly

  • Use coverage to find holes, not to prove quality. A test with no assertions executes code and raises coverage while checking nothing. Mutation testing tools such as PIT answer the question "would any test notice if this line were wrong?".
  • Set a threshold as a ratchet, not a goal. 0.80 on lines and a lower number on branches prevents regression; chasing 100% makes people write tests for getters.
  • Look at branches and at the red code, not only the headline number. The risky code (money, permissions, parsing) deserves more attention than the average.
  • Measure what you ship. Exclude generated code and pure configuration, but not "hard to test" business logic.
  • In CI, publish the HTML report as an artifact, or upload the XML to your code-quality service, so a pull request can show what changed.

Check your understanding

Quick check ยท 7 questions

of 7 answered You scored / 7 ยท perfect!

  1. 1. A test class has two @Test methods, one @BeforeEach and one @BeforeAll, with the default lifecycle. How many times does the constructor run?

    With the default PER_METHOD lifecycle JUnit creates a fresh instance for every test, so the constructor runs once per test. @BeforeAll is static and runs once without an instance.
  2. 2. Why must @BeforeAll methods normally be static?

    @BeforeAll runs before any instance exists. With @TestInstance(PER_CLASS) there is one shared instance, so @BeforeAll may then be an instance method.
  3. 3. In a @Nested class, which setup runs first for a nested test?

    Nested tests inherit the outer context. JUnit runs setup from the outermost class inward, and teardown from the innermost outward.
  4. 4. A test calls assumeTrue(false, "no database") in its first line. How is it reported?

    A failed assumption aborts the test. It is neither a pass nor a failure, which is why assumptions must not be used to hide real problems.
  5. 5. Which tests does the tag expression fast & !parsing select?

    & means both conditions must hold and ! negates a tag, so the test needs the fast tag and must not carry the parsing tag.
  6. 6. A suite class is annotated @Suite, @SelectPackages("com.example.shop") and @IncludeTags("smoke"). What does it run?

    Selectors say where to look and filters narrow the result, exactly like the discovery request a build tool creates.
  7. 7. A JaCoCo report shows a line in yellow with a diamond saying "1 of 2 branches missed". What does that mean?

    Yellow marks partly covered lines. A condition that tests only ever see as true (or only false) leaves a branch untested although the line counts as covered.

Summary

  • JUnit creates a new test instance per test method: constructor, @BeforeEach, test, @AfterEach. Fields never leak between tests; static fields do.
  • @BeforeAll and @AfterAll run once per class and are static, unless the class uses @TestInstance(PER_CLASS), which shares one instance and its fields.
  • @DisplayName and @DisplayNameGeneration make reports readable; @Nested inner classes group tests by situation and run outer setup before inner setup.
  • @Disabled("reason") and conditions such as @EnabledOnOs skip tests before they start; assumptions (assumeTrue, assumingThat) abort them from inside.
  • @Tag labels tests; Maven -Dgroups, Gradle includeTags and tag expressions with &, | and ! select them.
  • A @Suite class (from junit-platform-suite) selects tests with @SelectPackages/@SelectClasses and filters with @IncludeTags, @ExcludeTags and @IncludeClassNamePatterns; it is a discovery request written as annotations. Surefire's default includes don't match *Suite names.
  • JaCoCo (prepare-agent, report, check) shows which lines and branches tests executed; yellow lines are half-tested conditions. Use coverage to find untested code and as a ratchet threshold, not as proof of quality.
  • Don't rely on test order; use @TestMethodOrder only for genuine step-by-step scenarios, and @Timeout as a guard against hangs.

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