0
0
JUnittesting~10 mins

@ExtendWith annotation in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the @ExtendWith annotation in JUnit 5 to register a custom extension. It verifies that the extension's callback method is called during test execution.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import static org.junit.jupiter.api.Assertions.assertTrue;

class MyExtension implements BeforeEachCallback {
    static boolean beforeEachCalled = false;

    @Override
    public void beforeEach(ExtensionContext context) {
        beforeEachCalled = true;
    }
}

@ExtendWith(MyExtension.class)
public class ExtendWithTest {

    @Test
    void testExtensionCalled() {
        assertTrue(MyExtension.beforeEachCalled, "Extension beforeEach should have been called");
    }
}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1JUnit test runner starts the test class ExtendWithTestJUnit framework initialized, test class loaded-PASS
2JUnit detects @ExtendWith(MyExtension.class) and registers MyExtension as an extensionExtension MyExtension is ready to be called before each test-PASS
3JUnit calls MyExtension.beforeEach() before running testExtensionCalled()MyExtension.beforeEachCalled is set to true-PASS
4JUnit runs testExtensionCalled() methodTest method executingassertTrue(MyExtension.beforeEachCalled) verifies beforeEachCalled is truePASS
5JUnit completes testExtensionCalled() successfullyTest passed-PASS
Failure Scenario
Failing Condition: MyExtension.beforeEach() is not called before the test method
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @ExtendWith annotation do in this test?
AMarks the test method as disabled
BRegisters MyExtension to run before each test method
CSpecifies the test method's timeout
DInjects a mock object into the test
Key Result
Use @ExtendWith to add custom behavior before or after tests. Always verify that your extension's callbacks are executed as expected.