0
0
JUnittesting~10 mins

Why extensions customize JUnit behavior - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test checks how a JUnit extension customizes test behavior by adding a setup step before each test and verifying it runs correctly.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.extension.BeforeEachCallback;
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;

class CustomSetupExtension implements BeforeEachCallback {
    boolean setupDone = false;

    @Override
    public void beforeEach(ExtensionContext context) {
        setupDone = true; // Custom setup logic
    }
}

public class ExtensionBehaviorTest {

    @RegisterExtension
    static CustomSetupExtension extension = new CustomSetupExtension();

    @Test
    void testSetupIsDone() {
        assertTrue(extension.setupDone, "Setup should be done before test");
    }
}
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1JUnit test runner starts the ExtensionBehaviorTest classTest class loaded, extension registered-PASS
2JUnit calls beforeEach method of CustomSetupExtension before testSetupIsDoneExtension's setupDone flag set to true-PASS
3JUnit runs testSetupIsDone methodTest method executing with extension.setupDone == trueassertTrue(extension.setupDone) verifies setupDone is truePASS
4JUnit completes test and reports resultTest passed successfully-PASS
Failure Scenario
Failing Condition: Extension's beforeEach method does not run or does not set setupDone to true
Execution Trace Quiz - 3 Questions
Test your understanding
What does the CustomSetupExtension do before each test?
ASets a flag indicating setup is done
BSkips the test execution
CChanges the test method name
DThrows an exception
Key Result
JUnit extensions customize test behavior by hooking into lifecycle events like beforeEach, allowing reusable setup or teardown logic outside test methods.