Add beforeeach module: @BeforeEach/@AfterEach lifecycle demos on JUnit 6.1.3 (JDK 25)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b6FRR2Dk1163xJ5CdV
This commit is contained in:
2026-11-15 01:14:28 +05:30
co-authored by Claude Sonnet 5.5
parent bfc67986bc
commit e49be6d633
36 changed files with 690 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
target/
+13
View File
@@ -0,0 +1,13 @@
# JUnit @BeforeEach / @AfterEach demonstration
Runnable companion to the ankurm.com article
[JUnit @BeforeEach and @AfterEach](https://ankurm.com/junit-beforeeach-aftereach-complete-lifecycle-guide/).
`Fixtures.java` holds one small test class per scenario. `LifecycleOrderTest` runs each of them through the real JUnit
Launcher, asserts what happened and writes the event log to `output/`, so every transcript quoted in the article is also
an assertion that fails the build when it stops being true. Everything else (explanations, diagrams, the downloadable
real-world examples) lives in the article itself; this module has no separate docs.
Run: `mvn test` (JDK 17+). Same suite on JUnit 5: `mvn test -Djunit.version=5.14.4`.
Versions: JUnit 6.1.3 by default, run on JDK 25. Surefire 3.5.4.
+12
View File
@@ -0,0 +1,12 @@
new Sandwich()
@BeforeEach
@Test second
@AfterEach
new Sandwich()
@BeforeEach
@Test first
@AfterEach
-- results --
SUCCESSFUL second()
SUCCESSFUL first()
SUCCESSFUL Fixtures$Sandwich
+6
View File
@@ -0,0 +1,6 @@
addOne size=1
startsEmpty size=0
-- results --
SUCCESSFUL addOne()
SUCCESSFUL startsEmpty()
SUCCESSFUL Fixtures$FreshCart
@@ -0,0 +1,6 @@
a counter=1
b counter=1
-- results --
SUCCESSFUL a()
SUCCESSFUL b()
SUCCESSFUL Fixtures$FieldsDoNotLeak
+10
View File
@@ -0,0 +1,10 @@
Grandparent @BeforeEach
Parent @BeforeEach
Child @BeforeEach
Child @Test
Child @AfterEach
Parent @AfterEach
Grandparent @AfterEach
-- results --
SUCCESSFUL test()
SUCCESSFUL Fixtures$Child
+5
View File
@@ -0,0 +1,5 @@
OverrideSub.init
OverrideSub @Test
-- results --
SUCCESSFUL test()
SUCCESSFUL Fixtures$OverrideSub
@@ -0,0 +1,4 @@
OverrideNoAnnotationSub @Test
-- results --
SUCCESSFUL test()
SUCCESSFUL Fixtures$OverrideNoAnnotationSub
+6
View File
@@ -0,0 +1,6 @@
@BeforeEach
@Test boom
@AfterEach (runs although the test failed)
-- results --
FAILED boom() AssertionFailedError: this test is designed to fail
SUCCESSFUL Fixtures$FailingTest
+10
View File
@@ -0,0 +1,10 @@
@BeforeEach (about to fail)
@AfterEach, resource is null
@BeforeEach (about to fail)
@AfterEach, resource is null
-- results --
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
SUCCESSFUL Fixtures$BeforeEachFails
+7
View File
@@ -0,0 +1,7 @@
middle
zeta
alpha
@Test
-- results --
SUCCESSFUL test()
SUCCESSFUL Fixtures$TwoBeforeEach
+5
View File
@@ -0,0 +1,5 @@
@BeforeEach sees myTest() / myTest
@Test myTest
-- results --
SUCCESSFUL myTest()
SUCCESSFUL Fixtures$InjectsTestInfo
+9
View File
@@ -0,0 +1,9 @@
new PerClass()
@BeforeEach
a counter=1
@BeforeEach
b counter=2
-- results --
SUCCESSFUL a()
SUCCESSFUL b()
SUCCESSFUL Fixtures$PerClass
+13
View File
@@ -0,0 +1,13 @@
Outer @BeforeEach
Outer @Test
Outer @AfterEach
Outer @BeforeEach
Inner @BeforeEach
Inner @Test
Inner @AfterEach
Outer @AfterEach
-- results --
SUCCESSFUL outerTest()
SUCCESSFUL innerTest()
SUCCESSFUL Inner
SUCCESSFUL Fixtures$Outer
@@ -0,0 +1,10 @@
BeforeEachCallback
@BeforeEach
BeforeTestExecutionCallback
@Test
AfterTestExecutionCallback
@AfterEach
AfterEachCallback
-- results --
SUCCESSFUL test()
SUCCESSFUL Fixtures$WithExtension
+6
View File
@@ -0,0 +1,6 @@
@Test
@AfterEach closeDatabase (throws)
@AfterEach deleteFiles
-- results --
FAILED test() IllegalStateException: db close failed
SUCCESSFUL Fixtures$TwoAfterEach
@@ -0,0 +1,14 @@
== StaticBeforeEach
-- results --
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 = '']
at com.ankurm.tutorials.junit.beforeeach.Fixtures$StaticBeforeEach.setUp(SourceFile:0)
== NonVoidBeforeEach
-- results --
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 = '']
at com.ankurm.tutorials.junit.beforeeach.Fixtures$NonVoidBeforeEach.setUp(SourceFile:0)
@@ -0,0 +1,5 @@
private @BeforeEach ran
@Test
-- results --
SUCCESSFUL test()
SUCCESSFUL Fixtures$PrivateBeforeEach
@@ -0,0 +1,5 @@
created file
temp file exists after cleanup: false
-- results --
SUCCESSFUL writes()
SUCCESSFUL Fixtures$TempFileCleanup
+2
View File
@@ -0,0 +1,2 @@
LOG: Setting default API mock behavior...
Running: testServiceWithActiveApi()
+4
View File
@@ -0,0 +1,4 @@
Executing first test: Checking User creation
Cleaning up resources and resetting state...
Executing second test: Checking User deletion
Cleaning up resources and resetting state...
@@ -0,0 +1,4 @@
LOG: Cleaning tables and seeding User data...
Executing Test: findUserById()
LOG: Cleaning tables and seeding User data...
Executing Test: deleteUser()
@@ -0,0 +1,3 @@
Database connection established.
Testing user insertion logic...
Database connection closed.
@@ -0,0 +1 @@
Cleanup still happens, keeping the environment stable!
+1
View File
@@ -0,0 +1 @@
Deleted temporary file: test_report<random>.txt
@@ -0,0 +1,5 @@
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
@@ -0,0 +1,2 @@
LOG: Injecting 'ADMIN' security context...
Running: testAdminSensitiveOperation()
@@ -0,0 +1,4 @@
DEBUG: Setting up a fresh shopping cart...
DEBUG: Running testAddItem
DEBUG: Setting up a fresh shopping cart...
DEBUG: Running testCartIsInitiallyEmpty
@@ -0,0 +1,2 @@
app.ui.theme during test: DARK
app.ui.theme after cleanup: null
@@ -0,0 +1,2 @@
LOG: Created temporary directory: junit_test_9916606615363270050
Running: testFileWriteOperation()
@@ -0,0 +1 @@
INFO: Preparing environment for: cartStartsEmpty()
+53
View File
@@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurTutorials</groupId>
<artifactId>beforeeach-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- override with -Djunit.version=5.14.4 to run the same suite on JUnit 5 -->
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<!-- used by RunHelper to execute the deliberately failing fixtures programmatically -->
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.5.4</version>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,31 @@
package com.ankurm.tutorials.junit.beforeeach;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Ordered event log shared by the fixtures; the tests assert on it and write it to output/. */
public final class Events {
private static final List<String> LOG = new ArrayList<>();
private Events() {}
public static synchronized void add(String s) { LOG.add(s); }
public static synchronized void clear() { LOG.clear(); }
public static synchronized List<String> snapshot() { return new ArrayList<>(LOG); }
/** Writes the lines to output/&lt;name&gt; relative to the module directory. */
public static void write(String name, List<String> lines) {
try {
Path dir = Path.of("output");
Files.createDirectories(dir);
Files.write(dir.resolve(name), lines);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
@@ -0,0 +1,195 @@
package com.ankurm.tutorials.junit.beforeeach;
import static org.junit.jupiter.api.Assertions.fail;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
/**
* Small test classes that are executed by the real JUnit Launcher from LifecycleOrderTest.
* They are package-private and nested so Surefire does not run them on its own (the broken ones would fail the build).
*/
final class Fixtures {
private Fixtures() {}
private static void log(String s) { Events.add(s); }
/** The cart from the "fresh start" example. */
static class ShoppingCart {
private final java.util.List<String> items = new java.util.ArrayList<>();
void addItem(String item) { items.add(item); }
int getSize() { return items.size(); }
}
/** 1. The sandwich: a new instance, @BeforeEach, the test, @AfterEach, for every test method. */
static class Sandwich {
Sandwich() { log("new Sandwich()"); }
@BeforeEach void setUp() { log(" @BeforeEach"); }
@AfterEach void tearDown() { log(" @AfterEach"); }
@Test void first() { log(" @Test first"); }
@Test void second() { log(" @Test second"); }
}
/** 2. Why the setup matters: the cart is a fresh object for each test. */
static class FreshCart {
private ShoppingCart cart;
@BeforeEach void init() { cart = new ShoppingCart(); }
@Test void addOne() { cart.addItem("Laptop"); log("addOne size=" + cart.getSize()); }
@Test void startsEmpty() { log("startsEmpty size=" + cart.getSize()); }
}
/** 3. Instance fields do not survive from one test to the next under the default lifecycle. */
static class FieldsDoNotLeak {
int counter = 0;
@Test void a() { counter++; log("a counter=" + counter); }
@Test void b() { counter++; log("b counter=" + counter); }
}
/** 4. Inheritance: Grandparent -> Parent -> Child for setup, the reverse for teardown. */
static class Grandparent {
@BeforeEach void gSetup() { log("Grandparent @BeforeEach"); }
@AfterEach void gTeardown() { log("Grandparent @AfterEach"); }
}
static class Parent extends Grandparent {
@BeforeEach void pSetup() { log("Parent @BeforeEach"); }
@AfterEach void pTeardown() { log("Parent @AfterEach"); }
}
static class Child extends Parent {
@BeforeEach void cSetup() { log("Child @BeforeEach"); }
@AfterEach void cTeardown() { log("Child @AfterEach"); }
@Test void test() { log("Child @Test"); }
}
/** 5. Overriding an @BeforeEach method silently replaces the superclass one (it is NOT called). */
static class OverrideBase {
@BeforeEach void init() { log("OverrideBase.init"); }
}
static class OverrideSub extends OverrideBase {
@Override @BeforeEach void init() { log("OverrideSub.init"); }
@Test void test() { log("OverrideSub @Test"); }
}
/** 5b. The same override without repeating @BeforeEach: the method is no longer a lifecycle method at all. */
static class OverrideNoAnnotationSub extends OverrideBase {
@Override void init() { log("OverrideNoAnnotationSub.init"); }
@Test void test() { log("OverrideNoAnnotationSub @Test"); }
}
/** 6. A failing test does not skip @AfterEach. */
static class FailingTest {
@BeforeEach void setUp() { log("@BeforeEach"); }
@AfterEach void tearDown() { log("@AfterEach (runs although the test failed)"); }
@Test void boom() { log("@Test boom"); fail("this test is designed to fail"); }
}
/** 7. A failing @BeforeEach: the test body never runs, but @AfterEach still does. */
static class BeforeEachFails {
private AutoCloseable resource;
@BeforeEach void setUp() { log("@BeforeEach (about to fail)"); throw new IllegalStateException("setup failed"); }
@AfterEach void tearDown() throws Exception {
log("@AfterEach, resource is " + (resource == null ? "null" : "set"));
resource.close(); // unguarded on purpose: NPE
}
@Test void a() { log("@Test a (must not appear)"); }
@Test void b() { log("@Test b (must not appear)"); }
}
/** 8. Several @BeforeEach methods in one class: all run, in a deterministic but not obvious order. */
static class TwoBeforeEach {
@BeforeEach void zeta() { log("zeta"); }
@BeforeEach void alpha() { log("alpha"); }
@BeforeEach void middle() { log("middle"); }
@Test void test() { log("@Test"); }
}
/** 9. TestInfo (and TestReporter) can be injected into @BeforeEach. */
static class InjectsTestInfo {
@BeforeEach void setUp(TestInfo info) { log("@BeforeEach sees " + info.getDisplayName() + " / " + info.getTestMethod().get().getName()); }
@Test void myTest() { log("@Test myTest"); }
}
/** 10. PER_CLASS: one instance, but @BeforeEach still runs before every test. */
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
static class PerClass {
int counter = 0;
PerClass() { log("new PerClass()"); }
@BeforeEach void setUp() { log("@BeforeEach"); }
@Test void a() { counter++; log("a counter=" + counter); }
@Test void b() { counter++; log("b counter=" + counter); }
}
/** 11. @Nested: outer @BeforeEach first, inner second; teardown in reverse. */
static class Outer {
@BeforeEach void outerSetUp() { log("Outer @BeforeEach"); }
@AfterEach void outerTearDown() { log("Outer @AfterEach"); }
@Test void outerTest() { log("Outer @Test"); }
@Nested class Inner {
@BeforeEach void innerSetUp() { log("Inner @BeforeEach"); }
@AfterEach void innerTearDown() { log("Inner @AfterEach"); }
@Test void innerTest() { log("Inner @Test"); }
}
}
/** 12. Where @BeforeEach sits among extension callbacks. */
static class Spy implements BeforeEachCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback, AfterEachCallback {
@Override public void beforeEach(ExtensionContext c) { log("BeforeEachCallback"); }
@Override public void beforeTestExecution(ExtensionContext c) { log("BeforeTestExecutionCallback"); }
@Override public void afterTestExecution(ExtensionContext c) { log("AfterTestExecutionCallback"); }
@Override public void afterEach(ExtensionContext c) { log("AfterEachCallback"); }
}
@ExtendWith(Spy.class)
static class WithExtension {
@BeforeEach void setUp() { log("@BeforeEach"); }
@AfterEach void tearDown() { log("@AfterEach"); }
@Test void test() { log("@Test"); }
}
/** 13. Two @AfterEach methods: one failing does not stop the other. */
static class TwoAfterEach {
@AfterEach void closeDatabase() { log("@AfterEach closeDatabase (throws)"); throw new IllegalStateException("db close failed"); }
@AfterEach void deleteFiles() { log("@AfterEach deleteFiles"); }
@Test void test() { log("@Test"); }
}
// ---- rules the engine enforces: each of these is rejected at discovery / execution time ----
static class PrivateBeforeEach {
@BeforeEach private void setUp() { log("private @BeforeEach ran"); }
@Test void test() { log("@Test"); }
}
static class StaticBeforeEach {
@BeforeEach static void setUp() { log("never runs"); }
@Test void test() { log("@Test"); }
}
static class NonVoidBeforeEach {
@BeforeEach String setUp() { log("never runs"); return "x"; }
@Test void test() { log("@Test"); }
}
/** 14. A cleaner that runs after a failing test and closes what the test created. */
static class TempFileCleanup {
private Path tempFile;
@Test void writes() throws Exception {
tempFile = Files.createTempFile("test_report", ".txt");
log("created " + (Files.exists(tempFile) ? "file" : "nothing"));
}
@AfterEach void deleteTempFiles() throws Exception {
if (tempFile != null) {
Files.deleteIfExists(tempFile);
log("temp file exists after cleanup: " + Files.exists(tempFile));
}
}
}
}
@@ -0,0 +1,177 @@
package com.ankurm.tutorials.junit.beforeeach;
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 java.util.List;
import org.junit.jupiter.api.Test;
/**
* Runs every fixture through the real Launcher, pins what happened, and writes the transcript to output/.
* Each transcript quoted in the article is therefore also an assertion that fails the build when it stops being true.
*/
class LifecycleOrderTest {
private static List<String> events(List<String> log) {
return log.subList(0, log.indexOf("-- results --"));
}
@Test
void sandwichRepeatsForEveryTestWithANewInstance() {
List<String> log = RunHelper.run(Fixtures.Sandwich.class);
Events.write("01-sandwich.txt", log);
// method order inside a class is deterministic but deliberately not obvious, so only the shape is pinned
List<String> e = events(log);
assertEquals(8, e.size());
for (int i = 0; i < 8; i += 4) {
assertEquals("new Sandwich()", e.get(i));
assertEquals(" @BeforeEach", e.get(i + 1));
assertTrue(e.get(i + 2).startsWith(" @Test "));
assertEquals(" @AfterEach", e.get(i + 3));
}
}
@Test
void freshCartEveryTime() {
List<String> log = RunHelper.run(Fixtures.FreshCart.class);
Events.write("02-fresh-cart.txt", log);
assertTrue(log.contains("addOne size=1"));
assertTrue(log.contains("startsEmpty size=0")); // whichever ran first, the cart was empty again
}
@Test
void instanceFieldsDoNotLeakBetweenTests() {
List<String> log = RunHelper.run(Fixtures.FieldsDoNotLeak.class);
Events.write("03-fields-do-not-leak.txt", log);
assertTrue(log.contains("a counter=1"));
assertTrue(log.contains("b counter=1"));
}
@Test
void setupRunsTopDownAndTeardownBottomUp() {
List<String> log = RunHelper.run(Fixtures.Child.class);
Events.write("04-inheritance.txt", log);
assertEquals(List.of("Grandparent @BeforeEach", "Parent @BeforeEach", "Child @BeforeEach", "Child @Test",
"Child @AfterEach", "Parent @AfterEach", "Grandparent @AfterEach"), events(log));
}
@Test
void overridingABeforeEachMethodReplacesTheSuperclassOne() {
List<String> log = RunHelper.run(Fixtures.OverrideSub.class);
Events.write("05-override.txt", log);
assertEquals(List.of("OverrideSub.init", "OverrideSub @Test"), events(log));
}
@Test
void overridingWithoutTheAnnotationDropsTheHookEntirely() {
List<String> log = RunHelper.run(Fixtures.OverrideNoAnnotationSub.class);
Events.write("05b-override-no-annotation.txt", log);
assertEquals(List.of("OverrideNoAnnotationSub @Test"), events(log));
}
@Test
void afterEachRunsWhenTheTestFails() {
List<String> log = RunHelper.run(Fixtures.FailingTest.class);
Events.write("06-failing-test.txt", log);
assertEquals(List.of("@BeforeEach", "@Test boom", "@AfterEach (runs although the test failed)"), events(log));
assertTrue(log.stream().anyMatch(s -> s.startsWith("FAILED") && s.contains("boom")));
}
@Test
void failingBeforeEachSkipsTheTestBodyButNotAfterEach() {
List<String> log = RunHelper.run(Fixtures.BeforeEachFails.class);
Events.write("07-beforeeach-fails.txt", log);
List<String> e = events(log);
assertFalse(e.stream().anyMatch(s -> s.contains("must not appear")));
assertTrue(e.contains("@AfterEach, resource is null"));
// the real failure is the setup exception; the NullPointerException from the unguarded teardown is suppressed on it
assertTrue(log.stream().anyMatch(s -> s.contains("IllegalStateException: setup failed")));
assertTrue(log.stream().anyMatch(s -> s.contains("suppressed NullPointerException")));
}
@Test
void severalBeforeEachMethodsAllRun() {
List<String> log = RunHelper.run(Fixtures.TwoBeforeEach.class);
Events.write("08-two-beforeeach.txt", log);
List<String> e = events(log);
assertEquals(4, e.size());
assertEquals("@Test", e.get(3));
assertTrue(e.containsAll(List.of("zeta", "alpha", "middle")));
}
@Test
void beforeEachCanTakeTestInfo() {
List<String> log = RunHelper.run(Fixtures.InjectsTestInfo.class);
Events.write("09-testinfo.txt", log);
assertTrue(log.contains("@BeforeEach sees myTest() / myTest"));
}
@Test
void perClassKeepsOneInstanceButBeforeEachStillRunsEveryTime() {
List<String> log = RunHelper.run(Fixtures.PerClass.class);
Events.write("10-per-class.txt", log);
List<String> e = events(log);
assertEquals("new PerClass()", e.get(0));
assertEquals(1, e.stream().filter(s -> s.equals("new PerClass()")).count());
assertEquals(2, e.stream().filter(s -> s.equals("@BeforeEach")).count());
assertTrue(e.contains("a counter=1") || e.contains("a counter=2"));
assertTrue(e.contains("b counter=1") || e.contains("b counter=2"));
}
@Test
void nestedClassesRunOuterSetupFirstAndOuterTeardownLast() {
List<String> log = RunHelper.run(Fixtures.Outer.class);
Events.write("11-nested.txt", log);
int i = events(log).indexOf("Inner @Test");
List<String> e = events(log);
assertEquals(List.of("Outer @BeforeEach", "Inner @BeforeEach", "Inner @Test", "Inner @AfterEach", "Outer @AfterEach"),
e.subList(i - 2, i + 3));
}
@Test
void beforeEachSitsBetweenTheTwoExtensionCallbacks() {
List<String> log = RunHelper.run(Fixtures.WithExtension.class);
Events.write("12-extension-callbacks.txt", log);
assertEquals(List.of("BeforeEachCallback", "@BeforeEach", "BeforeTestExecutionCallback", "@Test",
"AfterTestExecutionCallback", "@AfterEach", "AfterEachCallback"), events(log));
}
@Test
void aFailingAfterEachDoesNotStopTheOthers() {
List<String> log = RunHelper.run(Fixtures.TwoAfterEach.class);
Events.write("13-two-aftereach.txt", log);
List<String> e = events(log);
assertTrue(e.contains("@AfterEach closeDatabase (throws)"));
assertTrue(e.contains("@AfterEach deleteFiles"));
assertTrue(log.stream().anyMatch(s -> s.startsWith("FAILED") && s.contains("db close failed")));
}
@Test
void staticAndNonVoidBeforeEachAreRejected() {
List<String> all = new java.util.ArrayList<>();
for (Class<?> c : new Class<?>[] {Fixtures.StaticBeforeEach.class, Fixtures.NonVoidBeforeEach.class}) {
all.add("== " + c.getSimpleName());
List<String> log = RunHelper.run(c);
all.addAll(log);
assertFalse(events(log).contains("never runs"));
assertTrue(log.stream().anyMatch(s -> s.startsWith("FAILED") || s.startsWith("ABORTED")), c.getSimpleName());
}
Events.write("14-rejected-signatures.txt", all);
}
@Test
void privateBeforeEachStillRunsInJUnit6ButIsDeprecated() {
// JUnit 6.1.x only logs a discovery warning ("should not be private ... disallowed in a future release")
List<String> log = RunHelper.run(Fixtures.PrivateBeforeEach.class);
Events.write("14b-private-beforeeach.txt", log);
assertTrue(events(log).contains("private @BeforeEach ran"));
}
@Test
void tempFileIsDeletedByAfterEach() {
List<String> log = RunHelper.run(Fixtures.TempFileCleanup.class);
Events.write("15-temp-file-cleanup.txt", log);
assertEquals(List.of("created file", "temp file exists after cleanup: false"), events(log));
}
}
@@ -0,0 +1,56 @@
package com.ankurm.tutorials.junit.beforeeach;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
import java.util.ArrayList;
import java.util.List;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
/** Runs fixture classes through the real Launcher and returns the events plus per-node results. */
final class RunHelper {
private RunHelper() {}
private static String describe(Throwable t) {
StringBuilder sb = new StringBuilder(" " + t.getClass().getSimpleName() + ": " + t.getMessage());
for (Throwable s : t.getSuppressed())
sb.append("\n suppressed ").append(s.getClass().getSimpleName()).append(": ").append(s.getMessage());
return sb.toString();
}
static List<String> run(Class<?>... classes) {
return run(java.util.Map.of(), classes);
}
static List<String> run(java.util.Map<String, String> config, Class<?>... classes) {
Events.clear();
var b = LauncherDiscoveryRequestBuilder.request();
for (Class<?> c : classes) b.selectors(selectClass(c));
config.forEach(b::configurationParameter);
LauncherDiscoveryRequest request = b.build();
List<String> results = new ArrayList<>();
TestExecutionListener l = new TestExecutionListener() {
@Override
public void executionSkipped(TestIdentifier id, String reason) {
results.add("SKIPPED " + id.getDisplayName());
}
@Override
public void executionFinished(TestIdentifier id, TestExecutionResult r) {
boolean root = id.getParentId().isEmpty();
if (root && r.getStatus() == TestExecutionResult.Status.SUCCESSFUL) return; // engine root, nothing to say
String what = r.getThrowable().map(RunHelper::describe).orElse("");
results.add(String.format("%-10s %s%s", r.getStatus(), root ? "<engine>" : id.getDisplayName(), what));
}
};
LauncherFactory.create().execute(request, l);
List<String> all = new ArrayList<>(Events.snapshot());
all.add("-- results --");
all.addAll(results);
return all;
}
}