Lifecycle: @BeforeEach, @AfterEach, @BeforeAll
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A ShopLite test passes when run alone but fails in the full suite. The cause is almost always one test leaving data behind for the next.
A new test-class instance per test method
Per-method lifecycle is JUnit 5's default: it creates a new instance of the test class for every test method, so instance fields are fresh in every test and a value set in one test is gone in the next.
Two tests use the same cart field. Run them and watch how many test objects JUnit creates.
Example 1 · One new test object per test method
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.MethodName.class) // a predictable order for this demo onlyclass InstancePerTestTest {
static int objectsCreated = 0; private final Cart cart = new Cart(); // a field: fresh for every test
InstancePerTestTest() { objectsCreated++; System.out.println("new test object #" + objectsCreated); }
@Test void a_addTwoPens() { cart.add("PEN-BLU", new BigDecimal("10.00"), 2); System.out.println(" a: items in this cart = " + cart.itemCount()); assertEquals(2, cart.itemCount()); }
@Test void b_cartStartsEmpty() { System.out.println(" b: items in this cart = " + cart.itemCount()); assertEquals(0, cart.itemCount()); }}new test object #1 a: items in this cart = 2 new test object #2 b: items in this cart = 0 [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.041 s -- in com.shoplite.cart.InstancePerTestTest
What this code does
- JUnit created two test objects, one per test method, so the
cartfield is a different empty cart in each test. Testbsees 0 items even though testaran first and added 2. @TestMethodOrder(MethodOrderer.MethodName.class)sorts the tests by name only so that this printout is predictable; normal tests must not depend on any order.
The order in which JUnit runs the test methods of a class is fixed but deliberately not obvious (it is not the order in the file). Never write a test that needs another test to run first. When a demo needs a predictable order, @TestMethodOrder(MethodOrderer.MethodName.class) sorts the tests by name.
Predict the output
Does the second test see the first?
Test a runs first. Pick what test b prints.
Round 1 of 2
The list is an instance field.
@BeforeEach and @AfterEach for fresh fixtures
Fixture is the set of objects a test works on, such as a cart with two items. A method marked @BeforeEach builds it before every test, and @AfterEach cleans up after every test, even a failed one.
Three tests all start with the same cart. Build it once in a @BeforeEach method instead of copying the lines into every test.
Example 2 · @BeforeEach builds the same fixture for every test
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;
class CartWithItemsTest {
private Cart cart;
@BeforeEach void createCartWithANotebookAndPens() { cart = new Cart(); cart.add("NB-A5", new BigDecimal("60.00"), 1); cart.add("PEN-BLU", new BigDecimal("10.00"), 3); }
@Test void itemCountAddsQuantities() { assertEquals(4, cart.itemCount()); }
@Test void removingThePensLeavesTheNotebook() { cart.remove("PEN-BLU");
assertEquals(new BigDecimal("60.00"), cart.total()); }
@Test void addingMorePensMergesIntoTheSameLine() { cart.add("PEN-BLU", new BigDecimal("10.00"), 2);
assertEquals(2, cart.lines().size()); assertEquals(5, cart.lines().get(1).quantity()); }}[INFO] Running com.shoplite.cart.CartWithItemsTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.045 s -- in com.shoplite.cart.CartWithItemsTest
What this code does
createCartWithANotebookAndPensruns before each of the three tests, so each test starts with exactly one notebook and three pens, whatever the other tests did.removingThePensLeavesTheNotebookchanges its cart, andaddingMorePensMergesIntoTheSameLinestill finds three pens: the removal happened on another test's cart.
The fixture lives in an instance field that @BeforeEach assigns. Each test gets a new instance and a fresh @BeforeEach run, so every test starts from the same known state.
Order of execution
Order the calls for one test
Tap the steps in the order JUnit runs them for one test method.
@BeforeAll and @AfterAll: once per class
PER_CLASS is the test instance lifecycle chosen with @TestInstance(TestInstance.Lifecycle.PER_CLASS): JUnit creates one instance for the whole class, so @BeforeAll can be a normal method and instance fields are shared by all tests.
Some set-up is slow and never changes, such as loading a price list. @BeforeAll runs it once for the whole class.
Example 3 · @BeforeAll: static, or an instance method with PER_CLASS
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;import java.util.Map;
import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestInstance;
class PriceListTest {
private static Map<String, BigDecimal> prices;
@BeforeAll static void loadPriceList() { System.out.println("loading price list once"); prices = Map.of("NB-A5", new BigDecimal("60.00"), "PEN-BLU", new BigDecimal("10.00")); }
@Test void notebookPrice() { assertEquals(new BigDecimal("60.00"), prices.get("NB-A5")); }
@Test void penPrice() { assertEquals(new BigDecimal("10.00"), prices.get("PEN-BLU")); }}
@TestInstance(TestInstance.Lifecycle.PER_CLASS)class PriceListPerClassTest {
private Map<String, BigDecimal> prices; // one instance for the whole class
@BeforeAll void loadPriceList() { // allowed: not static with PER_CLASS prices = Map.of("NB-A5", new BigDecimal("60.00")); }
@Test void notebookPrice() { assertEquals(new BigDecimal("60.00"), prices.get("NB-A5")); }}loading price list once [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.039 s -- in com.shoplite.cart.PriceListTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 s -- in com.shoplite.cart.PriceListPerClassTest # If loadPriceList() in PriceListTest were not static, discovery stops with: (1) [ERROR] @BeforeAll method 'void com.shoplite.cart.PriceListTest.loadPriceList()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).
What this code does
- "loading price list once" prints a single time for two tests:
@BeforeAllruns once per class. The map is built once and only read, so sharing it is safe. (Two test classes in one file is just for this example; in a project each gets its own file.) - Without
static, JUnit reports the error shown while it discovers the tests (the exact wrapper text differs a little between JUnit versions), because under the default per-method lifecycle there is no instance yet.PER_CLASScreates one instance, so an instance method works.
With the default per-method lifecycle, @BeforeAll and @AfterAll must be static, because no test instance exists yet when they run.
@TestInstance(PER_CLASS) lets them be normal instance methods. The price is that instance fields are shared by all tests, so every test must leave them as it found them.
Fix the error
Fix the @BeforeAll method
Read the error JUnit reports, then pick the line that fixes it.
The price list should load once for the whole class.
Error
@BeforeAll method 'void PriceListTest.loadPriceList()' must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS).
Shared mutable state and order-dependent failures
Shared mutable state is data that several tests can change: a static field, a field of a PER_CLASS test instance, a singleton or a database row. One test's change is seen by the next, so results depend on the order the tests run in.
A static cart is shared by two tests. In one order both pass; in the other order the second one fails.
Example 4 · Shared state: a static cart makes the result depend on order
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Order;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) // force one order to show the problemclass LeakyCartTest {
private static final Cart CART = new Cart(); // shared by every test: the bug
@Test @Order(1) void addingTwoPensCountsTwo() { CART.add("PEN-BLU", new BigDecimal("10.00"), 2);
assertEquals(2, CART.itemCount()); }
@Test @Order(2) void aNotebookCosts60() { CART.add("NB-A5", new BigDecimal("60.00"), 1);
assertEquals(new BigDecimal("60.00"), CART.total()); }}[ERROR] Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.048 s <<< FAILURE! -- in com.shoplite.cart.LeakyCartTest [ERROR] com.shoplite.cart.LeakyCartTest.aNotebookCosts60 -- Time elapsed: 0.005 s <<< FAILURE! org.opentest4j.AssertionFailedError: expected: <60.00> but was: <80.00>
What this code does
- Both tests use the same
staticcart, so the second test sees the two pens from the first: 60.00 + 20.00 = 80.00. Run alone,aNotebookCosts60passes; in this order it fails. - The fix is one change:
private Cart cart;assigned in a@BeforeEachmethod (or a non-static field initialiser), so each test gets its own cart. Remove the@Orderannotations too: correct tests need no order.
Such tests pass alone, fail together, or fail only after someone renames a method (which changes the default order). The fix is to build mutable fixtures in @BeforeEach as instance fields, keep static and @BeforeAll data read-only, and reset anything outside the JVM (files, tables) before each test.
Find the bug
Find the leak
Tap the line that lets one test change what the next one sees.
Run together, emptyCartTotalsZero fails after addPens.
Printing the lifecycle order
Lifecycle is the fixed order in which JUnit runs a test class: @BeforeAll once, then for each test a new object, @BeforeEach, the test and @AfterEach, and finally @AfterAll once.
Print a line from every lifecycle method and the order becomes visible.
Example 5 · The whole lifecycle, printed by JUnit
Runs in: a Maven project with JUnit 5 (shoplite-api: src/test/java/com/shoplite/cart)
package com.shoplite.cart;
import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.MethodOrderer;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.TestMethodOrder;
@TestMethodOrder(MethodOrderer.MethodName.class)class LifecycleOrderTest {
LifecycleOrderTest() { System.out.println(" constructor"); }
@BeforeAll static void beforeAll() { System.out.println("@BeforeAll"); }
@BeforeEach void beforeEach() { System.out.println(" @BeforeEach"); }
@Test void first() { System.out.println(" test first"); }
@Test void second() { System.out.println(" test second"); }
@AfterEach void afterEach() { System.out.println(" @AfterEach"); }
@AfterAll static void afterAll() { System.out.println("@AfterAll"); }}@BeforeAll
constructor
@BeforeEach
test first
@AfterEach
constructor
@BeforeEach
test second
@AfterEach
@AfterAllWhat this code does
@BeforeAlland@AfterAllrun once around everything; the constructor,@BeforeEachand@AfterEachrun once per test, because each test gets its own object.@AfterEachalso runs when a test fails, which is why it is the right place for clean-up such as deleting a temporary file.
Example 6 · The same order in plain Java: lifecycle methods are just calls
import java.util.List;
class PriceTests { static void beforeAll() { System.out.println("@BeforeAll load price list"); } static void afterAll() { System.out.println("@AfterAll close price list"); }
private StringBuilder cart;
void beforeEach() { cart = new StringBuilder("cart:"); System.out.println(" @BeforeEach fresh " + cart); } void afterEach() { System.out.println(" @AfterEach done with " + cart); }
void addPen() { cart.append(" pen"); System.out.println(" test addPen -> " + cart); } void addBook() { cart.append(" book"); System.out.println(" test addBook -> " + cart); }}
public class LifecycleByHand { public static void main(String[] args) { PriceTests.beforeAll(); for (String test : List.of("addPen", "addBook")) { PriceTests instance = new PriceTests(); // a new object per test instance.beforeEach(); try { if (test.equals("addPen")) instance.addPen(); else instance.addBook(); } finally { instance.afterEach(); // runs even if the test throws } } PriceTests.afterAll(); }}@BeforeAll load price list
@BeforeEach fresh cart:
test addPen -> cart: pen
@AfterEach done with cart: pen
@BeforeEach fresh cart:
test addBook -> cart: book
@AfterEach done with cart: book
@AfterAll close price listWhat this code does
- This is the lifecycle with no JUnit at all: a static set-up, then for each test a new object, set-up, the test inside
try, clean-up infinally, and a static tear-down at the end. - Because each test gets a new
PriceTestsobject,addBookseescart: book, notcart: pen book. That is exactly why JUnit's per-method lifecycle keeps tests isolated.
Under the hood these are ordinary method calls that JUnit makes in a fixed order, so the second program imitates them with a few lines of plain Java. @AfterEach runs even when a test fails, which is why it is the place for clean-up.
Next step
Check your understanding
10 quick questions