Sub topic 8
Setup and Teardown with Lifecycle Methods
Many tests in a class need the same starting objects. You might need a fresh list, a new Calculator, or a file to read. You could write that setup code at the top of every test, but copying the same lines again and again is slow and easy to get wrong. JUnit gives you lifecycle methods so you write the setup once.
A lifecycle method is a method that JUnit calls automatically at a fixed moment, such as before each test or after all tests. You never call it yourself. You only mark it with an annotation.
What a Fixture Is
A test fixture is the known starting state a test needs. It can be objects, data, or files. Every test should start from the same clean fixture. Then the result of one test cannot leak into another.
Lifecycle methods are where you build fixtures and clean them up:
- Setup builds the fixture before a test runs.
- Teardown cleans up after a test finishes. It closes files, clears data, or frees resources.
The Four Lifecycle Annotations
JUnit 5 has four main lifecycle annotations.
| Annotation | When JUnit runs it | Must it be `static`? | Typical use |
|---|---|---|---|
| `@BeforeEach` | Before every `@Test` method | No | Build a fresh fixture |
| `@AfterEach` | After every `@Test` method | No | Clean up that fixture |
| `@BeforeAll` | Once, before any test in the class | Yes (by default) | Start something slow and shared |
| `@AfterAll` | Once, after all tests in the class | Yes (by default) | Shut down the shared thing |
All four methods must return void and must not be private. They usually take no parameters.
A Worked Example with @BeforeEach and @AfterEach
Here is a test class for a shopping list. Each test needs a list that already holds "milk".
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class ShoppingListTest {
private List<String> items;
@BeforeEach
void setUp() {
items = new ArrayList<>();
items.add("milk");
}
@AfterEach
void tearDown() {
items.clear();
}
@Test
void addingAnItemGrowsTheList() {
items.add("bread");
assertAll(
() -> assertEquals(2, items.size()),
() -> assertTrue(items.contains("bread")));
}
@Test
void removingAnItemShrinksTheList() {
items.remove("milk");
assertEquals(0, items.size());
}
}Here is what happens step by step:
- JUnit calls
setUp(). The list now holds"milk". - JUnit runs one test, for example
addingAnItemGrowsTheList(). The list grows to 2 items. - JUnit calls
tearDown(). The list is cleared. - JUnit calls
setUp()again. A brand new list holds just"milk". - JUnit runs the other test. It removes
"milk"and sees size 0. - JUnit calls
tearDown()again.
The second test does not care what the first test did. Each test gets its own fresh list. That is the whole point of @BeforeEach.
JUnit Makes a New Object for Every Test
There is a detail here that surprises many beginners. By default, JUnit creates a new instance of your test class for every test method. An instance is one object made from a class.
So in ShoppingListTest, the items field belongs to a different object in each test. Even without tearDown(), the second test would never see the first test's bread. In this example, tearDown() is mostly there to show the idea. Teardown really matters when a test touches something outside the object, like a file, a network connection, or a static variable.
This "one instance per test" rule also explains the static rule for @BeforeAll and @AfterAll. Those methods run once for the whole class, before any test object exists. So they cannot belong to a single object. They must be static, which means they belong to the class itself.
Seeing the Order for Yourself
The best way to learn the order is to print it. Run this class:
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.Test;
class LifecycleOrderTest {
@BeforeAll
static void beforeAll() {
System.out.println("beforeAll");
}
@BeforeEach
void beforeEach() {
System.out.println(" beforeEach");
}
@Test
void firstTest() {
System.out.println(" firstTest");
}
@Test
void secondTest() {
System.out.println(" secondTest");
}
@AfterEach
void afterEach() {
System.out.println(" afterEach");
}
@AfterAll
static void afterAll() {
System.out.println("afterAll");
}
}The output looks like this:
beforeAll
beforeEach
firstTest
afterEach
beforeEach
secondTest
afterEach
afterAllJUnit may run secondTest before firstTest. The order of test methods is fixed from run to run, but JUnit does not promise it matches the order in your file. Your tests should never depend on running in a certain order.
When to Use @BeforeAll
Use @BeforeAll only for things that are slow to create and safe to share. A good example is starting an in-memory database or loading a large, read-only data file. If you create it once instead of once per test, the test run finishes sooner.
Shared state comes with a risk. If one test changes the shared object, the next test sees that change. Then the tests depend on each other, and a failure can appear or vanish depending on the order. Keep things that @BeforeAll creates read-only whenever you can. For anything a test changes, use @BeforeEach.
Changing the Instance Rule with @TestInstance
You can tell JUnit to make only one test object for the whole class:
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SharedSetupTest {
private List<String> colors;
@BeforeAll
void loadColors() {
colors = new ArrayList<>(List.of("red", "green", "blue"));
}
@Test
void containsRed() {
assertTrue(colors.contains("red"));
}
}With PER_CLASS, @BeforeAll and @AfterAll no longer need static, because one object lives for the whole class. The cost is that fields are now shared between tests. Use PER_CLASS only when you have a clear reason, and stick with the default for most classes.
Edge Cases Worth Knowing
- A test fails.
@AfterEachstill runs. That way your cleanup happens even when an assertion fails. @BeforeEachthrows an exception. JUnit does not run the test body and reports the test as failed.@AfterEachmethods still run, so write teardown that works even if setup stopped halfway. For example, check fornullbefore you close something.- Several methods with the same annotation. You may have two
@BeforeEachmethods in one class. JUnit runs both, but it does not promise which runs first. If the order matters, put the code in one method. - Inheritance. If your test class extends a base class, the base class's
@BeforeEachruns before the subclass's@BeforeEach. The base class's@AfterEachruns after the subclass's. Setup works from the outside in, and teardown works from the inside out. - Too much setup. If
@BeforeEachbuilds objects that only one test uses, readers must scroll up to understand that test. Put setup in@BeforeEachonly if most tests need it. Keep special setup inside the test that needs it.
Exercises
Exercise
A class has three @Test methods, one @BeforeEach method, and one @BeforeAll method. With the default settings, how many times does each lifecycle method run?
Show answer
@BeforeEach runs 3 times, once before each test. @BeforeAll runs 1 time, before any test starts.
Exercise
You write @BeforeAll void startServer() { ... } with no other changes, and JUnit reports an error. Give two different ways to fix it.
Show answer
Make the method static (@BeforeAll static void startServer()), or add @TestInstance(TestInstance.Lifecycle.PER_CLASS) to the test class so one instance is shared and the method may be non-static.
Exercise
A teammate puts a shared ArrayList in @BeforeAll. Each test adds items to it. Tests pass when run alone but fail when the whole class runs. Why, and what is the fix?
Show answer
All tests share one list, so items added by one test are still there in the next. Each test's result then depends on which tests ran before it. Create the list in @BeforeEach instead, so every test gets a fresh, empty list.
Exercise
An assertion in a test fails. Does the @AfterEach method still run? Why does that matter?
Show answer
Yes. JUnit runs @AfterEach even after a failure, so cleanup such as closing a connection or deleting data always happens and does not affect later tests.