Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 29 ยท JUnit core

Lifecycle, Nested Tests and Display Names

Understand the JUnit 6 test lifecycle: @BeforeEach, @AfterEach, @BeforeAll, @AfterAll, per-method instances, @Nested groups, @DisplayName, @Disabled and ordering.

Once you have more than a few tests, two problems show up at the same time. First, many tests need the same setup: a fresh object, a cleared list, an open resource. Second, a flat list of fifty methods in one class reads like a junk drawer. JUnit has a small set of annotations that solve both, and they all revolve around one question: what runs when?

This lesson answers that with real runs. You will watch the lifecycle callbacks print their own order, group tests into a readable specification with @Nested and @DisplayName, and switch tests off or put them in order when you must. It builds on JUnit Assertions in Depth.

The four lifecycle annotations

Four hooks around your tests

@BeforeAll Once, before the first test. Static.
@BeforeEach Before every single test.
@AfterEach After every test, even a failed one.
@AfterAll Once, after the last test. Static.

Use BeforeEach by default; BeforeAll is for costly setup.

1 / 2

The rules, in order, for each @Test method:

  1. JUnit creates a new instance of the test class.
  2. It runs every @BeforeEach method.
  3. It runs the test.
  4. It runs every @AfterEach method, even if the test failed.

Around that loop, @BeforeAll runs once before the first test and @AfterAll once after the last one. Because they run without a test instance, they must be static (unless you change the lifecycle, shown later).

The example prints a line from every callback, so you can see the order. The tests use MethodOrderer.MethodName so they run alphabetically and the output is easy to follow. The last test fails on purpose to prove that @AfterEach still runs.

Java Watching the lifecycle callbacks

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.

Read the output from top to bottom. The constructor line appears three times, once per test, and counter is 1 every time, which is what "fresh instance" means in practice. @BeforeAll and @AfterAll appear exactly once. The failing test still triggers @AfterEach, which is why cleanup belongs there and not at the end of the test body.

Which hook for what

  • Put cheap, per-test setup in @BeforeEach (create the object under test, reset a fake). This keeps tests independent.
  • Put expensive, read-only setup in @BeforeAll (start an embedded database, load a big file). Everything that survives between tests must be safe to share.
  • Use @AfterEach to close or reset things a test opened, such as a temporary file or a thread.
  • Prefer not to put assertions in setup methods. A failure there is reported against the setup, not against a test, which is confusing.

A test class can also inherit lifecycle methods: superclass @BeforeEach methods run before the subclass ones, and @AfterEach runs in the reverse direction. Inheritance for shared setup works, but a helper method or a JUnit extension is usually clearer.

Per-class instances

If you really need one object for the whole class, annotate the class with @TestInstance(TestInstance.Lifecycle.PER_CLASS). JUnit then creates the instance once, so @BeforeAll and @AfterAll no longer have to be static, and instance fields survive between tests. This is also what lets tests run as a numbered scenario, as in the next example, which combines it with @Order and @Disabled.

Java PER_CLASS, @Order and @Disabled

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 tests pass, and the disabled one is reported as [SKIP] with its reason. A skipped test is visible in every report, which is the point: unlike a commented-out method, it keeps nagging until someone fixes it.

Tests that depend on each other's side effects are fragile: run one alone from your IDE and it fails. The PER_CLASS plus @Order pattern fits a few real cases (an expensive end-to-end flow, a step-by-step demo), but in everyday unit tests keep the default and make every test stand alone.

Test ordering

By default JUnit runs methods in a deterministic but intentionally non-obvious order, so no one can lean on it. When you must choose an order, add @TestMethodOrder with one of:

  • MethodOrderer.MethodName: alphabetical by method name.
  • MethodOrderer.DisplayName: alphabetical by display name.
  • MethodOrderer.OrderAnnotation: by the @Order(n) number (lower runs first).
  • MethodOrderer.Random: shuffled, handy for discovering hidden order dependencies. Pass the seed to reproduce a failure.

An order is also useful when the fastest-failing tests should run first. Do not use ordering as a substitute for independence.

Readable names with @DisplayName

A method name like rejectsPercentAboveOneHundred is fine for developers. When reports go to a wider audience, or the sentence reads badly as camelCase, set a display name:

Java
@DisplayName("a stack that has been emptied")
class EmptiedStackTest {

    @Test
    @DisplayName("refuses to pop and says why")
    void popThrows() { ... }
}

Display names may contain spaces, punctuation and emoji, and they show up in IDEs, Maven reports and our runner's tree. They are labels only: JUnit still identifies the method by its real name. A class-level generator such as @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class) turns empty_stack_is_empty into empty stack is empty without annotating every method.

Grouping with @Nested

A @Nested class is a non-static inner class of a test class. It can have its own @BeforeEach, and it inherits those of the enclosing class, so a context is built layer by layer: the outer setup creates the object, the nested setup puts it into a particular state. The result reads like a specification: "Given a stack, when it is empty, it should...".

In the example, the outer @BeforeEach creates an empty stack, and the nested class WhenItHasItems pushes two values first. Watch how the tree mirrors the structure and uses the display names.

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 report prints the sentence names, with the two nested contexts indented under the outer class. Each nested test runs with both @BeforeEach methods: the stack is created, then filled. Notice that the outer test startsEmpty does not see the pushed items; only tests inside WhenItHasItems do.

Use @Nested when one class has several distinct situations (empty, full, error state). If you only need a second class to share setup, an ordinary separate test class is simpler.

Disabling tests: @Disabled

@Disabled("reason") skips a test method or a whole class. Always give a reason, ideally with a ticket number. The test is reported as skipped, not silently absent. Conditional skipping (only on Windows, only when an environment variable is set) uses the annotations in Conditions, Tags and Selecting Tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test class has an instance field int counter = 0 and a @BeforeEach that increments it. Three tests each assert that the counter equals 1. What happens with the default lifecycle?

    By default JUnit uses a fresh instance per test method, so instance fields start over each time.
  2. 2. Why must @BeforeAll methods be static in the default lifecycle?

    @BeforeAll runs once before the first test and before an instance has been created. With @TestInstance(PER_CLASS) there is a single instance and the methods can be non-static.
  3. 3. A test fails. Does @AfterEach still run?

    Cleanup in @AfterEach is guaranteed after each test, pass or fail, which is why it is the right place for it.
  4. 4. What is true about a @Nested class?

    @Nested classes are non-static inner classes. Outer setup runs first, then the nested class's own setup, building up the context.
  5. 5. What does @DisplayName("refuses to pop") change?

    A display name is purely a label for humans; discovery, ordering and selection still use the real method.

Summary

  • For every test JUnit creates a new instance, runs @BeforeEach, the test, then @AfterEach (even after a failure); @BeforeAll and @AfterAll bracket the whole class.
  • Put per-test setup in @BeforeEach; share only expensive, read-only things with @BeforeAll or @TestInstance(PER_CLASS).
  • @TestMethodOrder sets an order when you need one; default order is deterministic but not meaningful.
  • @DisplayName renames tests for reports; @Nested inner classes build contexts layer by layer and read like a specification.
  • @Disabled("reason") skips a test visibly; keep every test independent of the others.

Next: Conditions, Tags and Selecting Tests, for running the right tests in the right place.