0
0
JUnittesting~10 mins

Extension model overview in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how to use JUnit 5 extension model to log test execution start and end. It verifies that the extension methods are called during the test lifecycle.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.*;

class LoggingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {
    @Override
    public void beforeTestExecution(ExtensionContext context) {
        System.out.println("Starting test: " + context.getDisplayName());
    }

    @Override
    public void afterTestExecution(ExtensionContext context) {
        System.out.println("Finished test: " + context.getDisplayName());
    }
}

@ExtendWith(LoggingExtension.class)
public class ExtensionModelTest {

    @Test
    void sampleTest() {
        Assertions.assertTrue(1 + 1 == 2);
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1JUnit test runner starts the test suiteJUnit framework initialized, test class ExtensionModelTest loaded-PASS
2JUnit detects @ExtendWith annotation and registers LoggingExtensionLoggingExtension instance ready to intercept test lifecycle events-PASS
3JUnit calls LoggingExtension.beforeTestExecution before sampleTest runsConsole prints: "Starting test: sampleTest()"Verify beforeTestExecution callback is invokedPASS
4JUnit executes sampleTest methodTest method runs, assertion 1 + 1 == 2 evaluatedAssertTrue passes as 1 + 1 equals 2PASS
5JUnit calls LoggingExtension.afterTestExecution after sampleTest completesConsole prints: "Finished test: sampleTest()"Verify afterTestExecution callback is invokedPASS
6JUnit test runner completes the test suiteTest report generated showing sampleTest passedTest result is PASSPASS
Failure Scenario
Failing Condition: If the LoggingExtension is not registered or its methods throw exceptions
Execution Trace Quiz - 3 Questions
Test your understanding
What does the LoggingExtension.beforeTestExecution method do in this test?
APrints a message before the test method runs
BRuns the test assertion
CPrints a message after the test method runs
DSkips the test method
Key Result
Using JUnit 5 extensions allows you to add custom behavior before and after tests, improving test reporting and setup without changing test code.