Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01KqJyCidz3ZgRyHABv2GVJh
JUnit @BeforeAll / @AfterAll Demonstration
Runnable companion to the ankurm.com article "JUnit @BeforeAll and @AfterAll: One-Time Setup and Teardown".
Every scenario is a small fixture class in Fixtures.java. The real tests execute each fixture through the
JUnit Launcher, assert on what happened, and write the event log to output/, so each transcript quoted in
the article is also an assertion that fails the build when it stops being true.
Versions
| Item | Version |
|---|---|
JUnit (default, junit.version) |
6.1.3 (Jupiter, Platform, Launcher) |
| Also run green on | 5.14.4 (mvn test -Djunit.version=5.14.4; see note on SharedServerExtension) |
| Java | 17 language level (maven.compiler.release), run on JDK 25.0.4.1 |
| Maven Surefire | 3.5.4 |
Scenarios
| Fixture | What it shows | Output |
|---|---|---|
StaticHooks |
default lifecycle: static hooks, a new instance per test | 01-static-default.txt |
PerClassHooks |
@TestInstance(PER_CLASS): instance hooks, one shared instance |
02-per-class.txt |
NonStaticWithoutPerClass |
the classic mistake; discovery fails | 03-non-static-rejected.txt |
BeforeAllFails |
failing @BeforeAll skips tests, @AfterAll still runs |
04-beforeall-fails.txt |
BeforeAllFailsUnguarded |
unguarded @AfterAll NPE is attached as suppressed |
05-afterall-unguarded.txt |
AfterAllThrows |
one failing @AfterAll does not stop the next |
06-afterall-throws.txt |
Sub / Base |
inheritance order | 07-inheritance.txt |
HidingSub / HidingBase |
a hidden static @BeforeAll still runs |
08-hiding.txt |
TwoBeforeAllInOneClass |
order among several hooks in one class | 09-two-beforeall.txt |
OuterWithNested |
static @BeforeAll inside @Nested |
10-nested.txt |
SharedTempDir |
static @TempDir shared by the class |
11-shared-tempdir.txt |
UsesServerA / UsesServerB |
root-store AutoCloseable owned by an extension |
12-extension-store.txt |
NonStaticWithoutPerClass + config |
junit.jupiter.testinstance.lifecycle.default=per_class |
13-default-per-class-config.txt |
Note: SharedServerExtension uses Store.computeIfAbsent(Class), which exists from 6.0. On 5.14.x use
getOrComputeIfAbsent(Class) (deprecated since 6.0); with that one-word change the whole suite passes on 5.14.4.
Prerequisites
- JDK 17 or higher
- Maven 3.6+
How to Run
mvn test
The transcripts in output/ are regenerated by that command. Instance hash codes in 01 and 02 change per run.