diff --git a/beforeeach/.gitignore b/beforeeach/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/beforeeach/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/beforeeach/README.md b/beforeeach/README.md new file mode 100644 index 0000000..30dca21 --- /dev/null +++ b/beforeeach/README.md @@ -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. diff --git a/beforeeach/output/01-sandwich.txt b/beforeeach/output/01-sandwich.txt new file mode 100644 index 0000000..ce8c18b --- /dev/null +++ b/beforeeach/output/01-sandwich.txt @@ -0,0 +1,12 @@ +new Sandwich() + @BeforeEach + @Test second + @AfterEach +new Sandwich() + @BeforeEach + @Test first + @AfterEach +-- results -- +SUCCESSFUL second() +SUCCESSFUL first() +SUCCESSFUL Fixtures$Sandwich diff --git a/beforeeach/output/02-fresh-cart.txt b/beforeeach/output/02-fresh-cart.txt new file mode 100644 index 0000000..103066c --- /dev/null +++ b/beforeeach/output/02-fresh-cart.txt @@ -0,0 +1,6 @@ +addOne size=1 +startsEmpty size=0 +-- results -- +SUCCESSFUL addOne() +SUCCESSFUL startsEmpty() +SUCCESSFUL Fixtures$FreshCart diff --git a/beforeeach/output/03-fields-do-not-leak.txt b/beforeeach/output/03-fields-do-not-leak.txt new file mode 100644 index 0000000..ab77446 --- /dev/null +++ b/beforeeach/output/03-fields-do-not-leak.txt @@ -0,0 +1,6 @@ +a counter=1 +b counter=1 +-- results -- +SUCCESSFUL a() +SUCCESSFUL b() +SUCCESSFUL Fixtures$FieldsDoNotLeak diff --git a/beforeeach/output/04-inheritance.txt b/beforeeach/output/04-inheritance.txt new file mode 100644 index 0000000..ef9bdbb --- /dev/null +++ b/beforeeach/output/04-inheritance.txt @@ -0,0 +1,10 @@ +Grandparent @BeforeEach +Parent @BeforeEach +Child @BeforeEach +Child @Test +Child @AfterEach +Parent @AfterEach +Grandparent @AfterEach +-- results -- +SUCCESSFUL test() +SUCCESSFUL Fixtures$Child diff --git a/beforeeach/output/05-override.txt b/beforeeach/output/05-override.txt new file mode 100644 index 0000000..115241c --- /dev/null +++ b/beforeeach/output/05-override.txt @@ -0,0 +1,5 @@ +OverrideSub.init +OverrideSub @Test +-- results -- +SUCCESSFUL test() +SUCCESSFUL Fixtures$OverrideSub diff --git a/beforeeach/output/05b-override-no-annotation.txt b/beforeeach/output/05b-override-no-annotation.txt new file mode 100644 index 0000000..64d3152 --- /dev/null +++ b/beforeeach/output/05b-override-no-annotation.txt @@ -0,0 +1,4 @@ +OverrideNoAnnotationSub @Test +-- results -- +SUCCESSFUL test() +SUCCESSFUL Fixtures$OverrideNoAnnotationSub diff --git a/beforeeach/output/06-failing-test.txt b/beforeeach/output/06-failing-test.txt new file mode 100644 index 0000000..3e97d8a --- /dev/null +++ b/beforeeach/output/06-failing-test.txt @@ -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 diff --git a/beforeeach/output/07-beforeeach-fails.txt b/beforeeach/output/07-beforeeach-fails.txt new file mode 100644 index 0000000..1ed00eb --- /dev/null +++ b/beforeeach/output/07-beforeeach-fails.txt @@ -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 diff --git a/beforeeach/output/08-two-beforeeach.txt b/beforeeach/output/08-two-beforeeach.txt new file mode 100644 index 0000000..ab5a2f5 --- /dev/null +++ b/beforeeach/output/08-two-beforeeach.txt @@ -0,0 +1,7 @@ +middle +zeta +alpha +@Test +-- results -- +SUCCESSFUL test() +SUCCESSFUL Fixtures$TwoBeforeEach diff --git a/beforeeach/output/09-testinfo.txt b/beforeeach/output/09-testinfo.txt new file mode 100644 index 0000000..2c9c292 --- /dev/null +++ b/beforeeach/output/09-testinfo.txt @@ -0,0 +1,5 @@ +@BeforeEach sees myTest() / myTest +@Test myTest +-- results -- +SUCCESSFUL myTest() +SUCCESSFUL Fixtures$InjectsTestInfo diff --git a/beforeeach/output/10-per-class.txt b/beforeeach/output/10-per-class.txt new file mode 100644 index 0000000..5c2cd75 --- /dev/null +++ b/beforeeach/output/10-per-class.txt @@ -0,0 +1,9 @@ +new PerClass() +@BeforeEach +a counter=1 +@BeforeEach +b counter=2 +-- results -- +SUCCESSFUL a() +SUCCESSFUL b() +SUCCESSFUL Fixtures$PerClass diff --git a/beforeeach/output/11-nested.txt b/beforeeach/output/11-nested.txt new file mode 100644 index 0000000..903d43b --- /dev/null +++ b/beforeeach/output/11-nested.txt @@ -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 diff --git a/beforeeach/output/12-extension-callbacks.txt b/beforeeach/output/12-extension-callbacks.txt new file mode 100644 index 0000000..e372728 --- /dev/null +++ b/beforeeach/output/12-extension-callbacks.txt @@ -0,0 +1,10 @@ +BeforeEachCallback +@BeforeEach +BeforeTestExecutionCallback +@Test +AfterTestExecutionCallback +@AfterEach +AfterEachCallback +-- results -- +SUCCESSFUL test() +SUCCESSFUL Fixtures$WithExtension diff --git a/beforeeach/output/13-two-aftereach.txt b/beforeeach/output/13-two-aftereach.txt new file mode 100644 index 0000000..814f5d0 --- /dev/null +++ b/beforeeach/output/13-two-aftereach.txt @@ -0,0 +1,6 @@ +@Test +@AfterEach closeDatabase (throws) +@AfterEach deleteFiles +-- results -- +FAILED test() IllegalStateException: db close failed +SUCCESSFUL Fixtures$TwoAfterEach diff --git a/beforeeach/output/14-rejected-signatures.txt b/beforeeach/output/14-rejected-signatures.txt new file mode 100644 index 0000000..76b8e7b --- /dev/null +++ b/beforeeach/output/14-rejected-signatures.txt @@ -0,0 +1,14 @@ +== StaticBeforeEach +-- results -- +FAILED 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 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) diff --git a/beforeeach/output/14b-private-beforeeach.txt b/beforeeach/output/14b-private-beforeeach.txt new file mode 100644 index 0000000..c10df2f --- /dev/null +++ b/beforeeach/output/14b-private-beforeeach.txt @@ -0,0 +1,5 @@ +private @BeforeEach ran +@Test +-- results -- +SUCCESSFUL test() +SUCCESSFUL Fixtures$PrivateBeforeEach diff --git a/beforeeach/output/15-temp-file-cleanup.txt b/beforeeach/output/15-temp-file-cleanup.txt new file mode 100644 index 0000000..1f6020c --- /dev/null +++ b/beforeeach/output/15-temp-file-cleanup.txt @@ -0,0 +1,5 @@ +created file +temp file exists after cleanup: false +-- results -- +SUCCESSFUL writes() +SUCCESSFUL Fixtures$TempFileCleanup diff --git a/beforeeach/output/ex-ApiMockTest.txt b/beforeeach/output/ex-ApiMockTest.txt new file mode 100644 index 0000000..967b2d0 --- /dev/null +++ b/beforeeach/output/ex-ApiMockTest.txt @@ -0,0 +1,2 @@ +LOG: Setting default API mock behavior... +Running: testServiceWithActiveApi() diff --git a/beforeeach/output/ex-CleanupExample.txt b/beforeeach/output/ex-CleanupExample.txt new file mode 100644 index 0000000..0124a77 --- /dev/null +++ b/beforeeach/output/ex-CleanupExample.txt @@ -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... diff --git a/beforeeach/output/ex-DatabaseSeedTest.txt b/beforeeach/output/ex-DatabaseSeedTest.txt new file mode 100644 index 0000000..55bcf72 --- /dev/null +++ b/beforeeach/output/ex-DatabaseSeedTest.txt @@ -0,0 +1,4 @@ +LOG: Cleaning tables and seeding User data... +Executing Test: findUserById() +LOG: Cleaning tables and seeding User data... +Executing Test: deleteUser() diff --git a/beforeeach/output/ex-DatabaseServiceTest.txt b/beforeeach/output/ex-DatabaseServiceTest.txt new file mode 100644 index 0000000..2113d34 --- /dev/null +++ b/beforeeach/output/ex-DatabaseServiceTest.txt @@ -0,0 +1,3 @@ +Database connection established. +Testing user insertion logic... +Database connection closed. diff --git a/beforeeach/output/ex-FailingTestCleanup.txt b/beforeeach/output/ex-FailingTestCleanup.txt new file mode 100644 index 0000000..caa783e --- /dev/null +++ b/beforeeach/output/ex-FailingTestCleanup.txt @@ -0,0 +1 @@ +Cleanup still happens, keeping the environment stable! diff --git a/beforeeach/output/ex-FileServiceTest.txt b/beforeeach/output/ex-FileServiceTest.txt new file mode 100644 index 0000000..4c79122 --- /dev/null +++ b/beforeeach/output/ex-FileServiceTest.txt @@ -0,0 +1 @@ +Deleted temporary file: test_report.txt diff --git a/beforeeach/output/ex-InheritanceOrderTest.txt b/beforeeach/output/ex-InheritanceOrderTest.txt new file mode 100644 index 0000000..7fede4c --- /dev/null +++ b/beforeeach/output/ex-InheritanceOrderTest.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 diff --git a/beforeeach/output/ex-SecurityContextTest.txt b/beforeeach/output/ex-SecurityContextTest.txt new file mode 100644 index 0000000..a02aefd --- /dev/null +++ b/beforeeach/output/ex-SecurityContextTest.txt @@ -0,0 +1,2 @@ +LOG: Injecting 'ADMIN' security context... +Running: testAdminSensitiveOperation() diff --git a/beforeeach/output/ex-ShoppingCartTest.txt b/beforeeach/output/ex-ShoppingCartTest.txt new file mode 100644 index 0000000..0e5581d --- /dev/null +++ b/beforeeach/output/ex-ShoppingCartTest.txt @@ -0,0 +1,4 @@ +DEBUG: Setting up a fresh shopping cart... +DEBUG: Running testAddItem +DEBUG: Setting up a fresh shopping cart... +DEBUG: Running testCartIsInitiallyEmpty diff --git a/beforeeach/output/ex-SystemConfigTest.txt b/beforeeach/output/ex-SystemConfigTest.txt new file mode 100644 index 0000000..0a28c56 --- /dev/null +++ b/beforeeach/output/ex-SystemConfigTest.txt @@ -0,0 +1,2 @@ +app.ui.theme during test: DARK +app.ui.theme after cleanup: null diff --git a/beforeeach/output/ex-TempDirSetupTest.txt b/beforeeach/output/ex-TempDirSetupTest.txt new file mode 100644 index 0000000..0f01f08 --- /dev/null +++ b/beforeeach/output/ex-TempDirSetupTest.txt @@ -0,0 +1,2 @@ +LOG: Created temporary directory: junit_test_9916606615363270050 +Running: testFileWriteOperation() diff --git a/beforeeach/output/ex-TestInfoSetupTest.txt b/beforeeach/output/ex-TestInfoSetupTest.txt new file mode 100644 index 0000000..42912c6 --- /dev/null +++ b/beforeeach/output/ex-TestInfoSetupTest.txt @@ -0,0 +1 @@ +INFO: Preparing environment for: cartStartsEmpty() diff --git a/beforeeach/pom.xml b/beforeeach/pom.xml new file mode 100644 index 0000000..af15e2e --- /dev/null +++ b/beforeeach/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + com.ankurTutorials + beforeeach-demo + 1.0-SNAPSHOT + + + 17 + UTF-8 + + 6.1.3 + + + + + + org.junit + junit-bom + ${junit.version} + pom + import + + + + + + + org.junit.jupiter + junit-jupiter + test + + + + org.junit.platform + junit-platform-launcher + test + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.4 + + + + diff --git a/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/Events.java b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/Events.java new file mode 100644 index 0000000..5f904b2 --- /dev/null +++ b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/Events.java @@ -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 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 snapshot() { return new ArrayList<>(LOG); } + + /** Writes the lines to output/<name> relative to the module directory. */ + public static void write(String name, List lines) { + try { + Path dir = Path.of("output"); + Files.createDirectories(dir); + Files.write(dir.resolve(name), lines); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/Fixtures.java b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/Fixtures.java new file mode 100644 index 0000000..2f3ae92 --- /dev/null +++ b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/Fixtures.java @@ -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 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)); + } + } + } +} diff --git a/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/LifecycleOrderTest.java b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/LifecycleOrderTest.java new file mode 100644 index 0000000..34a18e2 --- /dev/null +++ b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/LifecycleOrderTest.java @@ -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 events(List log) { + return log.subList(0, log.indexOf("-- results --")); + } + + @Test + void sandwichRepeatsForEveryTestWithANewInstance() { + List 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 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 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 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 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 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 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 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 log = RunHelper.run(Fixtures.BeforeEachFails.class); + Events.write("07-beforeeach-fails.txt", log); + List 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 log = RunHelper.run(Fixtures.TwoBeforeEach.class); + Events.write("08-two-beforeeach.txt", log); + List e = events(log); + assertEquals(4, e.size()); + assertEquals("@Test", e.get(3)); + assertTrue(e.containsAll(List.of("zeta", "alpha", "middle"))); + } + + @Test + void beforeEachCanTakeTestInfo() { + List log = RunHelper.run(Fixtures.InjectsTestInfo.class); + Events.write("09-testinfo.txt", log); + assertTrue(log.contains("@BeforeEach sees myTest() / myTest")); + } + + @Test + void perClassKeepsOneInstanceButBeforeEachStillRunsEveryTime() { + List log = RunHelper.run(Fixtures.PerClass.class); + Events.write("10-per-class.txt", log); + List 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 log = RunHelper.run(Fixtures.Outer.class); + Events.write("11-nested.txt", log); + int i = events(log).indexOf("Inner @Test"); + List 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 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 log = RunHelper.run(Fixtures.TwoAfterEach.class); + Events.write("13-two-aftereach.txt", log); + List 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 all = new java.util.ArrayList<>(); + for (Class c : new Class[] {Fixtures.StaticBeforeEach.class, Fixtures.NonVoidBeforeEach.class}) { + all.add("== " + c.getSimpleName()); + List 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 log = RunHelper.run(Fixtures.PrivateBeforeEach.class); + Events.write("14b-private-beforeeach.txt", log); + assertTrue(events(log).contains("private @BeforeEach ran")); + } + + @Test + void tempFileIsDeletedByAfterEach() { + List 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)); + } +} diff --git a/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/RunHelper.java b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/RunHelper.java new file mode 100644 index 0000000..1547bd5 --- /dev/null +++ b/beforeeach/src/test/java/com/ankurm/tutorials/junit/beforeeach/RunHelper.java @@ -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 run(Class... classes) { + return run(java.util.Map.of(), classes); + } + + static List run(java.util.Map 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 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 ? "" : id.getDisplayName(), what)); + } + }; + LauncherFactory.create().execute(request, l); + List all = new ArrayList<>(Events.snapshot()); + all.add("-- results --"); + all.addAll(results); + return all; + } +}