Before and after every test

A test class often needs an object to call: a counter, a list, a service. Creating it in every test method repeats three lines, and creating it in a field once shares it between tests, so one test can change what the next one sees. @BeforeEach gives every test a fresh object, and @AfterEach is where the cleanup goes. The lifecycle article covers the same pair in a shorter form.

The shared field problem

Jupiter creates a new instance of the test class for every test method by default. A field initialized in the declaration therefore starts fresh in every test, but it is still built before the test knows which case it will run. A fixture that depends on the test, or that needs more than a constructor call, belongs in @BeforeEach.

The cleanup has the same shape. A test that opens a file, starts a server or changes a static value must put it back, and @AfterEach runs after every test whether it passed or failed. Without it, a red test leaves the mess for the next one and the second failure hides the first.

The class and the fixture

Counter.java has one counter and two methods. CounterTest.java keeps a Counter field, creates it in @BeforeEach and drops it in @AfterEach. Both test methods use the field as if it had just been constructed.

public class Counter { private int value; void increment() { value++; } int value() { return value; } }

import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class CounterTest { private Counter counter; @BeforeEach void createCounter() { counter = new Counter(); } @AfterEach void clearCounter() { counter = null; } @Test void startsAtZero() { assertEquals(0, counter.value()); } @Test void countsIncrements() { counter.increment(); counter.increment(); assertEquals(2, counter.value()); } }

@BeforeEach

A method marked @BeforeEach runs before every test method of the class. It may be package-private, it must return void, and it must not be static unless the class uses the per-class lifecycle of lesson 015. Several such methods may exist; their order is not specified, so they must not depend on each other.

The before method may also take parameters that JUnit can resolve, such as TestInfo or @TempDir, which later lessons use. The simple form with no parameters covers most fixtures.

@AfterEach

@AfterEach runs after every test, in the reverse order of the @BeforeEach methods when both are several. It runs after a passing test, after a failing assertion and after an unexpected exception, which makes it the place for a close or a delete. If the after method itself throws, the report shows that error and the test is red even when its body passed.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Counter.java CounterTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ CounterTest ✔
│     ├─ startsAtZero() ✔
│     └─ countsIncrements() ✔
└─ JUnit Vintage ✔

Test run finished after 613 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

The report does not name the before and after methods; it counts tests, not fixture calls. The two tests saw a new Counter each, which is why countsIncrements starts from zero even though another test ran first.

Exercises

  1. Remove @BeforeEach and run. Which test fails, and with what exception?
  2. Move the new Counter() into the field declaration and run. Do both tests still pass? Is that true for every class?
  3. Add a System.out.println in the before and after methods and run. Read the order of the four lines against the two tests.
  4. Make one test fail on purpose. Does the after method still run? How can you tell from the output?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How often does a @BeforeEach method run?

    Answer

    Once before every test method

    The method runs before each test, so every test starts from a fresh fixture.

  2. Does @AfterEach run when the test body fails?

    Answer

    Yes, it runs after a pass, a failure and an error

    The after method is part of the lifecycle, and Jupiter runs it whatever the test outcome.

  3. Why is the fixture created in @BeforeEach rather than in a field initializer?

    Answer

    It can depend on the test and can do more than a constructor call

    A fresh instance already gives a fresh field; the before method adds setup that the test chooses.

  4. What does this program print? public class Q1 { public static void main(String[] args) { int value = 0; value++; value++; System.out.println(value); } }

    Answer

    2

    Two increments take the value from 0 to 2.

  5. What does this program print? public class Q2 { public static void main(String[] args) { StringBuilder text = new StringBuilder(); text.append("a"); text.append("b"); System.out.println(text); } }

    Answer

    ab

    append adds to the same builder, and println prints its content.

  6. What does this program print? public class Q3 { static int value = 1; public static void main(String[] args) { value++; System.out.println(value); } }

    Answer

    2

    The static field starts at 1 and the increment makes it 2.

  7. What does this program print? public class Q4 { public static void main(String[] args) { int[] values = {1, 2}; values[0] = values[1]; System.out.println(values[0] + values[1]); } }

    Answer

    4

    The first element becomes 2, and the sum of 2 and 2 is 4.

  8. A test class has two @BeforeEach methods. What does JUnit promise about their order?

    Answer

    Nothing; they must not depend on each other

    The order of several before methods is not specified, so each must stand alone.

  9. What happens if an @AfterEach method throws?

    Answer

    The test is reported as failed even if its body passed

    A failing after method is part of the test outcome and turns it red.

  10. What does this program print? public class Q5 { public static void main(String[] args) { String name = "Ada"; name = name + "!"; System.out.println(name); } }

    Answer

    Ada!

    The second assignment builds a new string with the exclamation mark.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev