Skip to main content

JUnit @BeforeEach and @AfterEach (JUnit 5 and 6): Lifecycle Order with Examples

How @BeforeEach and @AfterEach really run in JUnit 5 and 6: a new instance per test, setup top-down and teardown bottom-up, what happens when setup fails, the override trap, and real database, mock, security and temp-file examples. Every transcript was run on JUnit 6.1.3 and every example can be downloaded.

Every JUnit test needs two things around it: a clean starting state, and a guarantee that whatever the test touched gets cleaned up afterwards. @BeforeEach and @AfterEach give you both. Used well, they turn a suite where order matters and tests fail for mysterious reasons into one where every test runs in isolation, pass or fail.

This guide starts from the one idea that explains almost everything about them (JUnit builds a brand-new test object for every test), then adds the rules the engine enforces, the real-world patterns (databases, mocks, security context, temp files), inheritance, and the traps. Every transcript below was produced by running the companion module, and every code sample can be downloaded as a real .java file.

Versions tested. Everything here was run on JUnit 6.1.3 (Jupiter, Platform and Launcher, the latest GA on Maven Central at the time of writing), JDK 25.0.5 (Temurin), Maven Surefire 3.5.4 and Java 17 as the language level (JUnit 6’s baseline). The same 17 tests also pass on JUnit 5.14.4, the last 5.x GA, with mvn test -Djunit.version=5.14.4. The annotations behave identically in both; the only difference you will meet is that 6.x logs a warning for a private lifecycle method (see the rules below). The JUnit 6 Test Lifecycle article covers @BeforeAll/@AfterAll and PER_CLASS in full.

Why every test gets a fresh start

By default JUnit creates a new instance of your test class for every @Test method (the PER_METHOD lifecycle). @BeforeEach runs on that new instance just before the test, and @AfterEach runs right after it. That is the whole mechanism, and it is why test isolation is the default rather than something you opt into.

One test method = one complete sandwichtest #1 (second())new instanceconstructor@BeforeEachsetUp()@Testsecond()@AfterEachtearDown()discardedgonetest #2 (first())new instanceconstructor@BeforeEachsetUp()@Testfirst()@AfterEachtearDown()discardedgoneBoth rows come from the transcript 01-sandwich.txt: the constructor runs again for every test,so a field set in one test cannot reach the next. (JUnit does not promise source order: in thereal run second() happened to go before first().)

The diagram shows two tests in one class. Each one gets its own new Sandwich(), its own @BeforeEach and its own @AfterEach. This is the real log, from 01-sandwich.txt (source: Fixtures.java):

new Sandwich()
  @BeforeEach
  @Test second
  @AfterEach
new Sandwich()
  @BeforeEach
  @Test first
  @AfterEach

The practical consequence is in 03-fields-do-not-leak.txt: two tests that each do counter++ on an instance field both see 1, because the field lives on an object that no longer exists by the next test.

a counter=1
b counter=1

The smallest example: a cart that is empty every time

Imagine testing a ShoppingCart. If one test adds a laptop and the next test expects an empty cart, the second must not see the first one’s laptop. A @BeforeEach that builds a new cart guarantees that. The class under test (Download ShoppingCart.java):

import java.util.ArrayList;
import java.util.List;

/** The class under test for the "fresh start" example. */
public class ShoppingCart {
    private final List<String> items = new ArrayList<>();

    public void addItem(String item) { items.add(item); }
    public int getSize() { return items.size(); }
    public void clear() { items.clear(); }
}

And the test (Download ShoppingCartTest.java):

package com.ankurm.testing;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class ShoppingCartTest {

    private ShoppingCart cart;

    @BeforeEach
    void init() {
        // This runs before EACH @Test method
        System.out.println("DEBUG: Setting up a fresh shopping cart...");
        cart = new ShoppingCart();
    }

    @Test
    @DisplayName("Should increment size when item is added")
    void testAddItem() {
        System.out.println("DEBUG: Running testAddItem");
        cart.addItem("Laptop");
        assertEquals(1, cart.getSize());
    }

    @Test
    @DisplayName("New cart should have zero items")
    void testCartIsInitiallyEmpty() {
        System.out.println("DEBUG: Running testCartIsInitiallyEmpty");
        assertEquals(0, cart.getSize());
    }
}

Real output, from ex-ShoppingCartTest.txt:

DEBUG: Setting up a fresh shopping cart...
DEBUG: Running testAddItem
DEBUG: Setting up a fresh shopping cart...
DEBUG: Running testCartIsInitiallyEmpty

Note the order of the two tests: JUnit’s default method order is deterministic but intentionally not source order (the sandwich log above ran second() first), so never write tests that depend on it. Keeping state in static fields would defeat all of this, which the troubleshooting table lists as a cause of leaks.

Going deeper: the PER_CLASS lifecycle (one instance, setup still per test)

You can ask JUnit to reuse one instance with @TestInstance(Lifecycle.PER_CLASS). @BeforeEach still runs before every test (it is per test, not per instance), but fields now survive between tests. From 10-per-class.txt: one constructor call, two @BeforeEach calls, and the counter climbs to 2.

new PerClass()
@BeforeEach
a counter=1
@BeforeEach
b counter=2

This is the one situation where an instance field can leak state between tests, so reset it in @BeforeEach. The whole PER_CLASS story (including making @BeforeAll non-static) is in the JUnit 6 Test Lifecycle article.

Going deeper: where these annotations came from (JUnit 4, 5 and 6)

@BeforeEach is the direct successor of JUnit 4’s @Before, and @AfterEach of @After. The names were made more descriptive in JUnit 5; the concept is identical in every version since, and JUnit 6 did not change it again.

JUnit 6 compatibility. Per JUnit 6’s release notes (not re-run here, so treat this as sourced from the notes rather than executed), the annotation model is untouched; the breaking changes in 6.0 are elsewhere: removed legacy modules, a stricter CSV parser, and a Java 17 baseline instead of JUnit 5’s Java 8. What was run for this article: the same 17 tests green on 6.1.3 and on 5.14.4, which is the practical proof that migrating does not change lifecycle behaviour. The migration playbook is in Refactoring Legacy Tests to JUnit 6.

What the engine requires of these methods

A lifecycle method is found by annotation, so it has to look the way the engine expects. Four rules, checked against a real run:

  1. Return void. A method that returns a value is rejected when JUnit scans the class.
  2. Not static. @BeforeEach needs the per-test instance. Static setup belongs to @BeforeAll. A static @BeforeEach is also rejected at scan time.
  3. Prefer package-private. public works, but package-private is the idiomatic style. A private method still ran in the real run, but JUnit 6.1 now logs a warning that it “should not be private” and will disallow it in a future release, so do not rely on it.
  4. It may throw. Checked and unchecked exceptions are both fine. If @BeforeEach throws, that test fails (it is not skipped or aborted) and its body never runs, but @AfterEach still does.
See the real error text for the rejected signatures

A rejected method does not fail one test quietly: the whole class fails at discovery, with a message that names the method. Quoted from 14-rejected-signatures.txt:

FAILED     <engine>  DiscoveryIssueException: TestEngine with ID 'junit-jupiter' encountered a critical issue during test discovery:

(1) [ERROR] @BeforeEach method 'static void com.ankurm.tutorials.junit.beforeeach.Fixtures$StaticBeforeEach.setUp()' must not be static.
    Source: MethodSource [className = 'com.ankurm.tutorials.junit.beforeeach.Fixtures$StaticBeforeEach', methodName = 'setUp', methodParameterTypes = '']

and for a method that returns a value:

FAILED     <engine>  DiscoveryIssueException: TestEngine with ID 'junit-jupiter' encountered a critical issue during test discovery:

(1) [ERROR] @BeforeEach method 'java.lang.String com.ankurm.tutorials.junit.beforeeach.Fixtures$NonVoidBeforeEach.setUp()' must not return a value.
    Source: MethodSource [className = 'com.ankurm.tutorials.junit.beforeeach.Fixtures$NonVoidBeforeEach', methodName = 'setUp', methodParameterTypes = '']

The private case, by contrast, only warns (14b-private-beforeeach.txt):

private @BeforeEach ran
@Test

So “my setup does not run” is rarely a visibility problem: a static or non-void method breaks the whole class loudly, and a private one still runs. The silent version of the bug is the override trap in the inheritance section.

Fingerprint of a failing @BeforeEach. When setup throws, every test in the class is reported FAILED with the setup exception, even though their bodies never ran. If your @AfterEach then dereferences something the setup never assigned, you also get a NullPointerException, attached to the real failure as a suppressed exception. Verbatim from 07-beforeeach-fails.txt:

@BeforeEach (about to fail)
@AfterEach, resource is null
@BeforeEach (about to fail)
@AfterEach, resource is null

The lines after the -- results -- marker in that file show the exception and the suppressed NullPointerException:

FAILED     a()  IllegalStateException: setup failed
             suppressed NullPointerException: Cannot invoke "java.lang.AutoCloseable.close()" because "this.resource" is null
FAILED     b()  IllegalStateException: setup failed
             suppressed NullPointerException: Cannot invoke "java.lang.AutoCloseable.close()" because "this.resource" is null

Setup patterns you will actually write

In real projects @BeforeEach does more than new an object. These four patterns cover most of what you will meet. Each one is a complete, compiled file you can download; the snippet shown is the setup method, and the output is what the file printed when run.

1. Seed the database before every test

When testing data-access code, every test needs the same known rows. The setup recreates them from scratch (Download DatabaseSeedTest.java, needs the H2 driver on the test classpath):

    @BeforeEach
    void initDatabase() throws SQLException {
        database = DriverManager.getConnection("jdbc:h2:mem:seed;DB_CLOSE_DELAY=-1", "sa", "");
        System.out.println("LOG: Cleaning tables and seeding User data...");
        execute("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, name VARCHAR(50))");
        execute("DELETE FROM users");
        execute("INSERT INTO users (id, name) VALUES (1, 'Ankur')");
    }

Output, from ex-DatabaseSeedTest.txt:

LOG: Cleaning tables and seeding User data...
Executing Test: findUserById()
LOG: Cleaning tables and seeding User data...
Executing Test: deleteUser()

The seed runs twice, once per test. If you only need the data loaded once and never modify it, move it to @BeforeAll.

2. Give your mocks a default behaviour

For a dependency on a third-party API (Stripe, Twilio), define the happy-path behaviour in @BeforeEach and override it in the few tests that need a failure (Download ApiMockTest.java, needs mockito-junit-jupiter):

    @Mock
    private ExternalApiClient apiClient;

    @BeforeEach
    void mockExternalApi() {
        System.out.println("LOG: Setting default API mock behavior...");
        when(apiClient.checkStatus()).thenReturn("ACTIVE");
    }

Output, from ex-ApiMockTest.txt:

LOG: Setting default API mock behavior...
Running: testServiceWithActiveApi()

Mockito creates the mock before your @BeforeEach runs, which is why the stubbing inside it works. See the Mockito 5 deep dive for strict stubs, which complain about stubs a test never uses.

3. Put a logged-in user in place

For Spring Security code, you often need an authenticated user before the test body runs. Because the security context is global (thread-local), pair it with an @AfterEach that clears it (Download SecurityContextTest.java, needs spring-security-core):

    @BeforeEach
    void authenticateUser() {
        System.out.println("LOG: Injecting 'ADMIN' security context...");
        SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken("admin", "password", List.of(new SimpleGrantedAuthority("ROLE_ADMIN")))
        );
    }

    @AfterEach
    void clearSecurityContext() {
        SecurityContextHolder.clearContext();
    }

Output, from ex-SecurityContextTest.txt:

LOG: Injecting 'ADMIN' security context...
Running: testAdminSensitiveOperation()
4. Prepare a temporary directory

File-handling tests need a directory that exists and is empty (Download TempDirSetupTest.java):

    private Path tempDir;

    @BeforeEach
    void prepareFileSystem() throws IOException {
        tempDir = Files.createTempDirectory("junit_test_");
        System.out.println("LOG: Created temporary directory: " + tempDir.getFileName());
    }

Output, from ex-TempDirSetupTest.txt (the number is random, so yours will differ):

LOG: Created temporary directory: junit_test_9916606615363270050
Running: testFileWriteOperation()

For new code, JUnit’s built-in @TempDir does the creation and the cleanup for you; the manual version above is worth knowing for older suites.

Parameters in a @BeforeEach method

Lifecycle methods can take parameters that JUnit resolves for you. The two you will use most are TestInfo (name and metadata of the current test) and TestReporter (publish extra info to the report). Here TestInfo is injected (Download TestInfoSetupTest.java):

    @BeforeEach
    void setup(TestInfo testInfo) {
        String displayName = testInfo.getDisplayName();
        System.out.println("INFO: Preparing environment for: " + displayName);
        this.cart = new ShoppingCart();
    }

Output, from ex-TestInfoSetupTest.txt, and the pinned assertion in 09-testinfo.txt:

INFO: Preparing environment for: cartStartsEmpty()
Going deeper: several @BeforeEach methods in one class

You may declare more than one. All of them run before each test, but the order between methods in the same class is deterministic and deliberately not obvious (it is not source order and not alphabetical). From 08-two-beforeeach.txt, for methods declared as zeta, alpha, middle:

middle
zeta
alpha
@Test

Treat that order as undefined. If one setup step must come before another, put both in one method.

Inheritance: parents set up first, tear down last

Shared setup usually lives in a base class. JUnit calls @BeforeEach methods from the top of the hierarchy down, so a child can safely use what its parent built. @AfterEach runs in exactly the reverse direction, so the child cleans up before the parent shuts down the infrastructure.

Setup runs top-down, teardown runs bottom-upGrandparentgSetup / gTeardownParentpSetup / pTeardownChildcSetup / cTeardown + @Test@BeforeEach1 Grandparent2 Parent3 Child@AfterEach5 Child6 Parent7 Grandparent(step 4 is the @Test itself)Verbatim order from 04-inheritance.txt. The child can rely on everything its parents built,and it tears its own things down first.

The numbers in the diagram are the order in which the methods ran. Here is the matching base and child (Download InheritanceOrderTest.java), with the real output from ex-InheritanceOrderTest.txt:

abstract class BaseTest {
    @BeforeEach
    void baseSetup() {
        System.out.println("BASE: Global Infrastructure Setup (e.g., Container Start)");
    }

    @AfterEach
    void baseTeardown() {
        System.out.println("BASE: Global Infrastructure Teardown");
    }
}

class InheritanceOrderTest extends BaseTest {
    @BeforeEach
    void specificSetup() {
        System.out.println("CHILD: Local Test Data Seeding (e.g., User Mocking)");
    }

    @AfterEach
    void specificTeardown() {
        System.out.println("CHILD: Local Test Data Cleanup");
    }

    @Test
    void myTest() {
        System.out.println("TEST: Execution of Business Logic Checks");
    }
}
BASE: Global Infrastructure Setup (e.g., Container Start)
CHILD: Local Test Data Seeding (e.g., User Mocking)
TEST: Execution of Business Logic Checks
CHILD: Local Test Data Cleanup
BASE: Global Infrastructure Teardown

The three-level version (Grandparent, Parent, Child) is pinned by an assertion and its transcript is 04-inheritance.txt; it is the source of the numbers in the diagram. The sequence repeats for every test in the child class.

Trap: overriding a hook replaces it. An @BeforeEach method that a subclass overrides is not called twice, it is replaced: the superclass version never runs. And if the override drops the annotation, the method stops being a lifecycle method at all, silently. Both verbatim from 05-override.txt and 05b-override-no-annotation.txt, where the base class has init() and the subclasses override it:

OverrideSub.init
OverrideSub @Test
OverrideNoAnnotationSub @Test
Give every hook in a hierarchy a unique name (baseSetup, specificSetup) and the problem cannot occur.
Going deeper: @Nested classes follow the same rule

A @Nested inner class counts as a child of its outer class: the outer @BeforeEach runs first, then the inner one; teardown goes inner first, then outer. From 11-nested.txt (the part for Inner @Test):

Outer @BeforeEach
Inner @BeforeEach
Inner @Test
Inner @AfterEach
Outer @AfterEach

That ordering is what lets a nested class add to the setup of the class around it without repeating it. The JUnit 6 nested tests guide builds on it.

@AfterEach: the cleanup that always runs

@AfterEach is the janitor. It runs after every test whether the test passed, failed an assertion or threw. Use it to release what a test or its setup acquired, so one test’s leftovers cannot break the next. A minimal one (Download CleanupExample.java):

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

public class CleanupExample {

    @AfterEach
    void tearDown() {
        // This runs after EVERY test method to ensure a clean slate
        System.out.println("Cleaning up resources and resetting state...");
    }

    @Test
    void firstTest() {
        System.out.println("Executing first test: Checking User creation");
    }

    @Test
    void secondTest() {
        System.out.println("Executing second test: Checking User deletion");
    }
}

Output, from ex-CleanupExample.txt:

Executing first test: Checking User creation
Cleaning up resources and resetting state...
Executing second test: Checking User deletion
Cleaning up resources and resetting state...

It runs even when the test fails

That is the guarantee that makes it the right place for cleanup. A test that fails on purpose (Download FailingTestCleanup.java):

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

/** Fails on purpose. Run it alone: mvn test -Dtest=FailingTestCleanup */
public class FailingTestCleanup {

    @Test
    void failingTest() {
        org.junit.jupiter.api.Assertions.fail("This test is designed to fail");
    }

    @AfterEach
    void alwaysRuns() {
        System.out.println("Cleanup still happens, keeping the environment stable!");
    }
}

The failure is reported, and the cleanup line is still printed (ex-FailingTestCleanup.txt); the same property is pinned with an assertion in 06-failing-test.txt:

Cleanup still happens, keeping the environment stable!

The flip side: because it also runs after a failed @BeforeEach, it cannot assume anything was created. That is the NullPointerException case above, and the reason for the null-check rule below.

Why and when

  • Strict isolation. The outcome of one test must not influence the next; test order should never matter.
  • Resource management. Close streams, sockets and connection pools opened during setup.
  • Safety net. If a test crashes halfway, the teardown still runs.
  • State reset. Clear static or shared state: a singleton’s registry, System properties, a security context.
  • Typical jobs: release database connections to the pool (avoids “too many connections”), delete temporary files, call Mockito.reset(mock) so interaction counts do not bleed into the next test, restore System.setProperty changes, and clear the SecurityContextHolder.
Real-world cleanup 1: closing a database connection

The classic integration-test leak is a connection that is never returned. Setup opens it, teardown closes it, with a guard so a failed setup does not turn into a second failure (Download DatabaseServiceTest.java, needs H2):

    private Connection connection;

    @BeforeEach
    void setUpConnection() throws SQLException {
        connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");
        System.out.println("Database connection established.");
    }

    @AfterEach
    void closeConnection() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            System.out.println("Database connection closed.");
        }
    }

Output, from ex-DatabaseServiceTest.txt:

Database connection established.
Testing user insertion logic...
Database connection closed.
Real-world cleanup 2: deleting temporary files

An undeleted temp file shows up later as “file already exists” or a full CI disk. Note the teardown relies on the field being set by the test, which is why it is null-checked (Download FileServiceTest.java):

    private Path tempFile;

    @Test
    void testFileWriting() throws IOException {
        tempFile = Files.createTempFile("test_report", ".txt");
        Files.writeString(tempFile, "Hello JUnit");
        // Assertions...
    }

    @AfterEach
    void deleteTempFiles() throws IOException {
        if (tempFile != null) {
            Files.deleteIfExists(tempFile);
            System.out.println("Deleted temporary file: " + tempFile.getFileName().toString().replaceAll("\\d{6,}", "<random>"));
        }
    }

Output, from ex-FileServiceTest.txt (the sample replaces the random digits in the file name with a fixed placeholder so the line is stable). The assertion that the file is really gone is in 15-temp-file-cleanup.txt:

Deleted temporary file: test_report<random>.txt
Real-world cleanup 3: restoring System properties

System.setProperty is global to the JVM, so a property one test sets leaks into every test that runs after it, in any class. Save it in @BeforeEach, restore it in @AfterEach (Download SystemConfigTest.java):

    private String originalTheme;

    @BeforeEach
    void storeOriginalState() {
        originalTheme = System.getProperty("app.ui.theme");
    }

    @AfterEach
    void restoreSystemProperties() {
        if (originalTheme != null) {
            System.setProperty("app.ui.theme", originalTheme);
        } else {
            System.clearProperty("app.ui.theme");
        }
        System.out.println("app.ui.theme after cleanup: " + System.getProperty("app.ui.theme"));
    }

    @Test
    void testDarkThemeActivation() {
        System.setProperty("app.ui.theme", "DARK");
        System.out.println("app.ui.theme during test: " + System.getProperty("app.ui.theme"));
    }

Output, from ex-SystemConfigTest.txt:

app.ui.theme during test: DARK
app.ui.theme after cleanup: null
Going deeper: a failing @AfterEach does not stop the others

If you have two @AfterEach methods and the first throws, the second still runs and the failure is reported. From 13-two-aftereach.txt:

@Test
@AfterEach closeDatabase (throws)
@AfterEach deleteFiles
-- results --
FAILED     test()  IllegalStateException: db close failed
SUCCESSFUL Fixtures$TwoAfterEach

That is a good reason to keep one responsibility per teardown method (database in one, files in another): a problem closing the database cannot stop the files being deleted.

The complete execution order, in one picture

Putting every piece together: instance creation, @BeforeEach, the test and @AfterEach (the sandwich at the start), plus the callbacks of any registered extension. Extensions such as Mockito or Spring hook in on both sides of your annotated methods, which is why a mock exists before your own setup runs.

Everything that happens around one test, in orderBeforeEachCallbackextension1@BeforeEachyour method2BeforeTestExecutionextension3@Testyour test4AfterTestExecutionextension5@AfterEachyour method6AfterEachCallbackextension7Blue and amber are the two annotations this article is about. The grey boxes only exist if anextension (Mockito, Spring, your own) is registered. They wrap the annotated methods on bothsides; the order is the real log in 12-extension-callbacks.txt.

The order in the diagram is not documented prose, it is the real log from 12-extension-callbacks.txt, produced by a small extension that records each callback:

BeforeEachCallback
@BeforeEach
BeforeTestExecutionCallback
@Test
AfterTestExecutionCallback
@AfterEach
AfterEachCallback
Going deeper: where this matters in practice

Two consequences. First, an extension’s BeforeEachCallback (Mockito initialising mocks, Spring injecting beans) has finished before your @BeforeEach starts, so you can use those objects there. Second, an AfterEachCallback runs after your @AfterEach, so the framework’s own cleanup happens last. The BeforeTestExecution/AfterTestExecution pair brackets only the test body, which is how timing extensions measure just the test and not your setup.

Best practices that come from the failures above

  1. Keep teardown fail-safe. Null-check every field in @AfterEach. It runs even if @BeforeEach failed before assigning anything.
  2. One responsibility per method. Two small @AfterEach methods (database, files) are safer than one, because a failure in the first does not stop the second.
  3. Unique, descriptive names. clearTemporaryFolders() beats tearDown(), and unique names avoid the override trap in the inheritance section.
  4. Keep it fast. A slow teardown multiplies by every test. Move heavy one-time work to @BeforeAll/@AfterAll.

Troubleshooting

SymptomCauseFix
The whole class fails at discovery@BeforeEach/@AfterEach is static or returns a value (see the real messages in the rules section).Make it a non-static void method.
Warning: “should not be private”Private lifecycle method; JUnit 6.1 still runs it but will disallow it.Make it package-private.
Setup silently never runsA subclass overrides the hook method, with or without repeating the annotation.Give every hook in a hierarchy a unique name.
Shared state leaks between testsstatic fields, or PER_CLASS instance fields not reset.Reset in @BeforeEach, or use instance fields under the default lifecycle.
Teardown throws NullPointerException@BeforeEach failed before assigning the resource but @AfterEach still ran.Null-check every field before using it.
Tests are slowHeavy database or network work in @BeforeEach.Move one-time setup to @BeforeAll.

At a glance

Feature@BeforeEach@AfterEach@BeforeAll
RunsBefore each testAfter each testOnce per class
PurposeSetup, initialisationCleanup, teardownExpensive one-time setup
Inheritance orderParent firstChild firstParent first
If it failsEach test fails, body skippedReported; other teardown still runsTests skipped
Method kindInstanceInstanceStatic (unless PER_CLASS)
Should you reach for these at all? For state that is cheap to build, a field initialiser or a plain helper called from the test is often clearer than a hidden @BeforeEach: the reader sees the setup next to the test that needs it. Use the annotations when setup is shared by many tests, or when cleanup must run even if the test throws. And if you find yourself writing a long @BeforeEach to make tests pass, the code under test usually has too many collaborators.

Summary

@BeforeEach and @AfterEach are two halves of one guarantee: every test starts from a clean slate and leaves nothing behind, pass or fail. They work because JUnit creates a new instance per test. Parents set up first and tear down last, a failing test never skips cleanup, and a failing setup still triggers teardown, so write teardown defensively.

Next step: look through your tests for setup repeated at the start of every @Test and resources closed at the end of test bodies. Move the first into @BeforeEach and the second into a null-safe @AfterEach.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.