Test Overview
This test demonstrates how BeforeEachCallback and AfterEachCallback work in JUnit 5. It verifies that setup code runs before each test and cleanup code runs after each test.
This test demonstrates how BeforeEachCallback and AfterEachCallback work in JUnit 5. It verifies that setup code runs before each test and cleanup code runs after each test.
import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class LifecycleExtensionTest { static class MyExtension implements BeforeEachCallback, AfterEachCallback { boolean beforeCalled = false; boolean afterCalled = false; @Override public void beforeEach(ExtensionContext context) { beforeCalled = true; System.out.println("BeforeEachCallback executed"); } @Override public void afterEach(ExtensionContext context) { afterCalled = true; System.out.println("AfterEachCallback executed"); } } @RegisterExtension static MyExtension extension = new MyExtension(); @Test void testOne() { assertTrue(extension.beforeCalled, "BeforeEachCallback should have run before testOne"); extension.beforeCalled = false; // reset for next test } @Test void testTwo() { assertTrue(extension.beforeCalled, "BeforeEachCallback should have run before testTwo"); extension.beforeCalled = false; // reset for next test } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit starts testOne | Test lifecycle begins for testOne | - | PASS |
| 2 | MyExtension.beforeEach() runs | beforeCalled flag set to true | - | PASS |
| 3 | testOne executes assertion on beforeCalled | beforeCalled is true | assertTrue(extension.beforeCalled) | PASS |
| 4 | testOne resets beforeCalled to false | beforeCalled reset | - | PASS |
| 5 | MyExtension.afterEach() runs after testOne | afterCalled flag set to true | - | PASS |
| 6 | JUnit starts testTwo | Test lifecycle begins for testTwo | - | PASS |
| 7 | MyExtension.beforeEach() runs | beforeCalled flag set to true | - | PASS |
| 8 | testTwo executes assertion on beforeCalled | beforeCalled is true | assertTrue(extension.beforeCalled) | PASS |
| 9 | testTwo resets beforeCalled to false | beforeCalled reset | - | PASS |
| 10 | MyExtension.afterEach() runs after testTwo | afterCalled flag set to true | - | PASS |