Test Overview
This test demonstrates how to use a custom JUnit 5 extension to measure and print the execution time of a test method. It verifies that the extension runs and the test passes.
This test demonstrates how to use a custom JUnit 5 extension to measure and print the execution time of a test method. It verifies that the extension runs and the test passes.
import org.junit.jupiter.api.extension.*; import org.junit.jupiter.api.*; class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace.create("timing"); @Override public void beforeTestExecution(ExtensionContext context) throws Exception { context.getStore(NAMESPACE).put("startTime", System.currentTimeMillis()); } @Override public void afterTestExecution(ExtensionContext context) throws Exception { long startTime = context.getStore(NAMESPACE).remove("startTime", Long.class); long duration = System.currentTimeMillis() - startTime; System.out.println("Test '" + context.getDisplayName() + "' took " + duration + " ms."); } } @ExtendWith(TimingExtension.class) public class CustomExtensionTest { @Test void sampleTest() { Assertions.assertTrue(2 + 2 == 4); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit test runner starts the test execution | JUnit framework initialized, test class loaded | - | PASS |
| 2 | JUnit calls TimingExtension.beforeTestExecution before sampleTest | Stores current time in extension context store | - | PASS |
| 3 | JUnit executes sampleTest method | Inside sampleTest, assertion checks if 2+2 equals 4 | assertTrue(2 + 2 == 4) | PASS |
| 4 | JUnit calls TimingExtension.afterTestExecution after sampleTest | Calculates elapsed time and prints it to console | - | PASS |
| 5 | JUnit completes test execution and reports results | Test passed, timing output visible in console | - | PASS |