JUnit Test Fixtures
A test fixture is the fixed starting state a test needs: the objects, data, files or connections that must exist before the test runs, and the cleanup that must happen after it. JUnit test fixtures are built with lifecycle methods such as @BeforeEach and @AfterEach, so the setup code is written once instead of being copied into every test.
This lesson covers the four JUnit lifecycle annotations, the order in which they run, sharing expensive setup with @BeforeAll, the PER_CLASS lifecycle, temporary files with @TempDir, fixtures in nested and inherited test classes, and test data builders. It ends with a fully fixtured test class for a file-based order store. The examples use the assertions from JUnit Assertions.
Why Tests Need Fixtures
Look at a test class without fixtures. Every test creates the same objects by hand:
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class RepeatedSetupTest {
@Test
void addsOneCourse() {
List<String> wishlist = new ArrayList<>();
wishlist.add("Java Basics");
wishlist.add("Python Basics");
wishlist.add("Go Basics");
assertEquals(3, wishlist.size());
}
@Test
void removesOneCourse() {
List<String> wishlist = new ArrayList<>();
wishlist.add("Java Basics");
wishlist.add("Python Basics");
wishlist.remove("Java Basics");
assertEquals(1, wishlist.size());
}
}
Output (mvn test, shortened):
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
How it works:
- Both tests pass, but the first three lines of each are identical.
- If the starting data changes, every test must be edited. With twenty tests this becomes error-prone.
- A fixture moves those lines into one place that JUnit runs automatically before each test.
JUnit Lifecycle Annotations
JUnit has four annotations for setup and cleanup:
| Annotation | Runs | Method must be | Typical use |
|---|---|---|---|
@BeforeEach | Before every test method | Instance method | Create fresh objects for each test |
@AfterEach | After every test method | Instance method | Clear state, close per-test resources |
@BeforeAll | Once before all tests in the class | static (by default) | Start an expensive shared resource |
@AfterAll | Once after all tests in the class | static (by default) | Stop the shared resource |
Like test methods, lifecycle methods must not be private and must return void.
Create a Fresh Fixture With @BeforeEach
@BeforeEach is the fixture you will use most. It runs before every test, so each test starts with a new, known state.
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.BeforeEach;
import org.junit.jupiter.api.Test;
class WishlistTest {
private List<String> wishlist;
@BeforeEach
void createWishlist() {
wishlist = new ArrayList<>(List.of("Java Basics", "Python Basics"));
}
@Test
void addsOneCourse() {
wishlist.add("Go Basics");
assertEquals(3, wishlist.size());
}
@Test
void removesOneCourse() {
wishlist.remove("Java Basics");
assertEquals(1, wishlist.size());
}
@Test
void startsWithJavaBasics() {
assertTrue(wishlist.contains("Java Basics"));
}
}
Output (mvn test, shortened):
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
How it works:
createWishlist()runs three times, once before each test, and assigns a new list to the field.startsWithJavaBasicspasses even if it runs afterremovesOneCourse, because it gets its own fresh list.- The tests now contain only the action and the check, which makes each one shorter and easier to read.
Clean Up With @AfterEach
@AfterEach runs after every test, even when the test fails. Use it to release resources the fixture created, such as open streams, threads or system properties.
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;
class SystemPropertyTest {
private String originalTimezone;
@BeforeEach
void setIndiaTimezone() {
originalTimezone = System.getProperty("user.timezone");
System.setProperty("user.timezone", "Asia/Kolkata");
System.out.println("before: timezone set");
}
@AfterEach
void restoreTimezone() {
if (originalTimezone == null) {
System.clearProperty("user.timezone");
} else {
System.setProperty("user.timezone", originalTimezone);
}
System.out.println("after: timezone restored");
}
@Test
void readsTimezone() {
assertEquals("Asia/Kolkata", System.getProperty("user.timezone"));
System.out.println("test: ran");
}
}
Output:
before: timezone set
test: ran
after: timezone restored
How it works:
- System properties are global to the JVM. Without cleanup, this test would change the environment for every test that runs after it.
@AfterEachputs back the original value, so the test leaves no trace.- If
assertEqualsfailed,restoreTimezonewould still run, just as afinallyblock would.
Share Expensive Setup With @BeforeAll and @AfterAll
Some setup is slow, such as starting an embedded server or loading a large file. Doing it before every test wastes time. @BeforeAll runs once for the whole class, and @AfterAll runs once at the end.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class PinCodeLookupTest {
private static Map<String, String> cityByPinCode;
@BeforeAll
static void loadPinCodes() throws InterruptedException {
Thread.sleep(300); // pretend to read a large CSV file
cityByPinCode = Map.of(
"600001", "Chennai",
"560001", "Bengaluru",
"110001", "New Delhi");
System.out.println("Loaded " + cityByPinCode.size() + " PIN codes once");
}
@AfterAll
static void releaseData() {
cityByPinCode = null;
System.out.println("Released PIN code data");
}
@Test
void findsChennai() {
assertEquals("Chennai", cityByPinCode.get("600001"));
}
@Test
void unknownPinIsMissing() {
assertNull(cityByPinCode.get("999999"));
}
}
Output:
Loaded 3 PIN codes once
Released PIN code data
How it works:
loadPinCodesandreleaseDataarestaticbecause JUnit calls them before any test instance exists.- The 300 ms load happens once, not twice. With fifty tests the saving is fifteen seconds.
- The shared data is read-only here. Never let tests modify data created in
@BeforeAll, or one test's changes will leak into the next.
Note:
@BeforeAllis for expensive, read-only or self-resetting resources. Anything a test changes belongs in@BeforeEach.
The Full JUnit Lifecycle Order
When all four annotations are present, JUnit runs them in a fixed order. This example prints each step so you can see it.
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 testA() {
System.out.println(" testA");
}
@Test
void testB() {
System.out.println(" testB");
}
@AfterEach
void afterEach() {
System.out.println(" @AfterEach");
}
@AfterAll
static void afterAll() {
System.out.println("@AfterAll");
}
}
Output:
@BeforeAll
constructor
@BeforeEach
testA
@AfterEach
constructor
@BeforeEach
testB
@AfterEach
@AfterAll
How it works:
@BeforeAllruns first, before any instance is created.- For each test, JUnit creates a new instance (the constructor runs), then calls
@BeforeEach, the test, and@AfterEach. @AfterAllruns last, after every test has finished.@TestMethodOrder(MethodOrderer.MethodName.class)only makes the printed order predictable; it is not needed for fixtures to work.
Use Non-Static @BeforeAll With PER_CLASS Lifecycle
@TestInstance(Lifecycle.PER_CLASS) tells JUnit to create one instance for the whole class. Then @BeforeAll and @AfterAll may be ordinary instance methods, and they can set instance fields.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
@TestInstance(Lifecycle.PER_CLASS)
class SharedExecutorTest {
private ExecutorService executor;
@BeforeAll
void startExecutor() {
executor = Executors.newFixedThreadPool(2);
System.out.println("executor started");
}
@AfterAll
void stopExecutor() {
executor.shutdown();
System.out.println("executor stopped");
}
@Test
void computesSquare() throws Exception {
Future<Integer> square = executor.submit(() -> 12 * 12);
assertEquals(144, square.get());
}
@Test
void computesLength() throws Exception {
Future<Integer> length = executor.submit(() -> "gocourse".length());
assertEquals(8, length.get());
}
}
Output:
executor started
executor stopped
How it works:
- With
PER_CLASS, the same object runs both tests, soexecutoris an instance field rather than astaticone. - The thread pool is created once and shut down once, which is the correct use of a shared, expensive resource.
- Because the instance is shared, any field a test changes stays changed for later tests. Keep per-test state in
@BeforeEacheven with this lifecycle.
Temporary Files With @TempDir
Tests that read or write files need a folder that is empty at the start and deleted at the end. @TempDir gives you exactly that. JUnit creates the directory before the test and deletes it, with everything inside, afterwards.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class ReportWriterTest {
@TempDir
Path workDir;
void writeReport(Path file, List<String> lines) throws IOException {
Files.write(file, lines);
}
@Test
void writesReportFile() throws IOException {
Path report = workDir.resolve("report.txt");
writeReport(report, List.of("Course,Students", "Java,120", "Python,95"));
assertTrue(Files.exists(report));
assertEquals(3, Files.readAllLines(report).size());
System.out.println("Wrote " + report.getFileName() + " in a temp folder");
}
@Test
void eachTestGetsAnEmptyFolder() throws IOException {
try (var files = Files.list(workDir)) {
assertEquals(0, files.count());
}
}
}
Output:
Wrote report.txt in a temp folder
How it works:
- An instance field annotated with
@TempDirgets a new directory for every test, soeachTestGetsAnEmptyFolderalways sees an empty folder. - You can also declare it as a test parameter:
void test(@TempDir Path dir). - A
static@TempDirfield is created once and shared by every test in the class. @TempDir(cleanup = CleanupMode.ON_SUCCESS)keeps the folder when a test fails, which helps you inspect what was written. The file handling itself is covered in the Java Files API lesson.
Fixtures in Nested and Inherited Test Classes
Lifecycle methods combine when classes are nested or extended. Outer and parent fixtures run first, then inner and child fixtures.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayDeque;
import java.util.Deque;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
abstract class BaseQueueTest {
protected Deque<String> queue;
@BeforeEach
void createQueue() {
queue = new ArrayDeque<>();
System.out.println("1. base: new queue");
}
}
class SupportTicketQueueTest extends BaseQueueTest {
@BeforeEach
void addFirstTicket() {
queue.offer("TICKET-1");
System.out.println("2. subclass: added TICKET-1");
}
@Nested
class WithTwoTickets {
@BeforeEach
void addSecondTicket() {
queue.offer("TICKET-2");
System.out.println("3. nested: added TICKET-2");
}
@Test
void servesOldestTicketFirst() {
assertEquals("TICKET-1", queue.poll());
assertEquals(1, queue.size());
System.out.println("4. test ran");
}
}
}
Output:
1. base: new queue
2. subclass: added TICKET-1
3. nested: added TICKET-2
4. test ran
How it works:
- The superclass
@BeforeEachruns before the subclass one, soqueuealready exists whenaddFirstTicketruns. - For a test inside a
@Nestedclass, the outer class's@BeforeEachmethods run first, then the nested class's. @AfterEachmethods run in the reverse order: nested first, then subclass, then superclass.- A base class like
BaseQueueTestis a simple way to share one fixture across many test classes.
Build Test Data With Factory Methods
Lifecycle methods create the state every test needs. When tests need slightly different objects, a small factory or builder method keeps the setup readable.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class EnrollmentRulesTest {
record Student(String name, int age, boolean feePaid, int completedCourses) {}
boolean canEnrollInAdvanced(Student student) {
return student.feePaid() && student.completedCourses() >= 2 && student.age() >= 16;
}
// Test data builder: valid by default, change only what the test cares about
static Student aStudent() {
return new Student("Asha", 21, true, 3);
}
static Student withFeePaid(Student s, boolean paid) {
return new Student(s.name(), s.age(), paid, s.completedCourses());
}
static Student withCompletedCourses(Student s, int count) {
return new Student(s.name(), s.age(), s.feePaid(), count);
}
@Test
void validStudentCanEnroll() {
assertTrue(canEnrollInAdvanced(aStudent()));
}
@Test
void unpaidFeeBlocksEnrollment() {
assertFalse(canEnrollInAdvanced(withFeePaid(aStudent(), false)));
}
@Test
void oneCompletedCourseIsNotEnough() {
Student student = withCompletedCourses(aStudent(), 1);
assertEquals(1, student.completedCourses());
assertFalse(canEnrollInAdvanced(student));
}
}
Output (mvn test, shortened):
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
How it works:
aStudent()returns a student who passes every rule. Each test changes exactly one field, so it is clear which rule is being tested.- If the
Studentrecord gains a new field later, only the factory methods change, not every test. - Records are immutable, so the
with...methods return new objects instead of modifying the shared default.
Real-World Example: JUnit Test Fixtures for a File-Based Order Store
This example tests a small class that stores orders in a CSV file. It uses a static fixture for shared reference data, a per-test temporary folder, a fresh store before every test, and cleanup checks after every test.
package com.gocourse.orders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
public class CsvOrderStore {
public record Order(String id, String customer, long amountInPaise) {}
private final Path file;
public CsvOrderStore(Path file) throws IOException {
this.file = file;
if (Files.notExists(file)) {
Files.writeString(file, "id,customer,amount\n");
}
}
public void save(Order order) throws IOException {
String line = order.id() + "," + order.customer() + "," + order.amountInPaise() + "\n";
Files.writeString(file, line, StandardOpenOption.APPEND);
}
public List<Order> findAll() throws IOException {
return Files.readAllLines(file).stream()
.skip(1) // header
.map(line -> line.split(","))
.map(p -> new Order(p[0], p[1], Long.parseLong(p[2])))
.toList();
}
public Optional<Order> findById(String id) throws IOException {
return findAll().stream().filter(o -> o.id().equals(id)).findFirst();
}
}
package com.gocourse.orders;
import static org.junit.jupiter.api.Assertions.*;
import com.gocourse.orders.CsvOrderStore.Order;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@DisplayName("CsvOrderStore")
class CsvOrderStoreTest {
// Shared, read-only reference data: created once
private static List<Order> sampleOrders;
@TempDir
Path tempDir; // new empty folder for every test
private Path ordersFile;
private CsvOrderStore store;
@BeforeAll
static void createSampleOrders() {
sampleOrders = List.of(
new Order("ORD-1", "Asha", 49_900),
new Order("ORD-2", "Ravi", 129_900),
new Order("ORD-3", "Meena", 9_900));
}
@BeforeEach
void openStore() throws IOException {
ordersFile = tempDir.resolve("orders.csv");
store = new CsvOrderStore(ordersFile);
}
@AfterEach
void fileStillHasHeader() throws IOException {
// A cleanup-time check: no test may corrupt the header line
assertEquals("id,customer,amount", Files.readAllLines(ordersFile).get(0));
}
@Test
@DisplayName("a new store creates the file with only a header")
void newStoreHasHeaderOnly() throws IOException {
assertTrue(Files.exists(ordersFile));
assertTrue(store.findAll().isEmpty());
}
@Test
@DisplayName("saved orders can be read back in order")
void savesAndReadsOrders() throws IOException {
for (Order order : sampleOrders) {
store.save(order);
}
assertIterableEquals(sampleOrders, store.findAll());
}
@Test
@DisplayName("finds an order by id")
void findsById() throws IOException {
store.save(sampleOrders.get(1));
Order found = store.findById("ORD-2").orElseThrow();
assertAll(
() -> assertEquals("Ravi", found.customer()),
() -> assertEquals(129_900, found.amountInPaise()));
}
@Test
@DisplayName("returns empty for an unknown id")
void unknownIdIsEmpty() throws IOException {
store.save(sampleOrders.get(0));
assertTrue(store.findById("ORD-404").isEmpty());
}
@Test
@DisplayName("reopening the same file keeps existing orders")
void reopenKeepsData() throws IOException {
store.save(sampleOrders.get(2));
CsvOrderStore reopened = new CsvOrderStore(ordersFile);
assertEquals(List.of(sampleOrders.get(2)), reopened.findAll());
}
}
Output in the Console Launcher:
└─ CsvOrderStore ✔
├─ a new store creates the file with only a header ✔
├─ saved orders can be read back in order ✔
├─ finds an order by id ✔
├─ returns empty for an unknown id ✔
└─ reopening the same file keeps existing orders ✔
[ 5 tests successful ]
[ 0 tests failed ]
How it works:
- Static shared data.
createSampleOrdersbuilds the immutableList.of(...)once. Tests read it but cannot change it, so sharing is safe. - Isolated files. The
@TempDirfield gives every test its own folder, so the orders saved insavesAndReadsOrdersnever appear innewStoreHasHeaderOnly, whatever order the tests run in. - Fresh store.
openStorecreates the CSV file and a newCsvOrderStorebefore each test, so the tests contain only the behaviour they check. - Checks during cleanup.
fileStillHasHeaderruns after every test. If any future change broke the header line, every test would fail at cleanup and point straight at the problem. - Automatic deletion. After each test, JUnit deletes the temporary folder and
orders.csvinside it, so nothing is left on disk.
With fixtures in place, the next step is to run the same test with many inputs. That is covered in JUnit Parameterized Tests.