0
0
JUnittesting~10 mins

Custom extensions in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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);
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1JUnit test runner starts the test executionJUnit framework initialized, test class loaded-PASS
2JUnit calls TimingExtension.beforeTestExecution before sampleTestStores current time in extension context store-PASS
3JUnit executes sampleTest methodInside sampleTest, assertion checks if 2+2 equals 4assertTrue(2 + 2 == 4)PASS
4JUnit calls TimingExtension.afterTestExecution after sampleTestCalculates elapsed time and prints it to console-PASS
5JUnit completes test execution and reports resultsTest passed, timing output visible in console-PASS
Failure Scenario
Failing Condition: The assertion in sampleTest fails (e.g., 2 + 2 != 4)
Execution Trace Quiz - 3 Questions
Test your understanding
What does the TimingExtension do before the test method runs?
AStores the current time to measure test duration
BPrints the test name to the console
CAsserts that the test will pass
DSkips the test execution
Key Result
Using custom extensions in JUnit allows you to add reusable behavior around tests, such as timing, logging, or resource management, improving test maintainability and clarity.