Bird
Raised Fist0
JUnittesting~15 mins

@ExtendWith annotation in JUnit - Build an Automation Script

Choose your learning style10 modes available
Automate a JUnit 5 test using @ExtendWith to register a custom extension
Preconditions (2)
Step 1: Create a test class named 'MyTestWithExtension'
Step 2: Annotate the test class with @ExtendWith(MyCustomExtension.class)
Step 3: Write a test method 'testExample' that asserts true is true
Step 4: Run the test class
✅ Expected Result: The test runs successfully with the custom extension applied, and the assertion passes
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the test method executes and passes
Verify that the custom extension is invoked (e.g., by a side effect or log)
Best Practices:
Use @ExtendWith annotation at class level
Keep test methods simple and focused
Use assertions from org.junit.jupiter.api.Assertions
Ensure the custom extension implements the Extension interface
Automated Solution
JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import static org.junit.jupiter.api.Assertions.assertTrue;

// Custom extension that prints a message before each test
class MyCustomExtension implements BeforeEachCallback {
    @Override
    public void beforeEach(ExtensionContext context) {
        System.out.println("Custom extension before each test method: " + context.getDisplayName());
    }
}

@ExtendWith(MyCustomExtension.class)
public class MyTestWithExtension {

    @Test
    void testExample() {
        assertTrue(true, "True should be true");
    }
}

This code defines a custom extension MyCustomExtension that implements BeforeEachCallback. It prints a message before each test method runs.

The test class MyTestWithExtension is annotated with @ExtendWith(MyCustomExtension.class) to register the extension.

The test method testExample simply asserts true is true, which always passes.

When running the test, the extension's beforeEach method runs first, printing the message, then the test runs and passes.

Common Mistakes - 4 Pitfalls
{'mistake': 'Not annotating the test class or method with @ExtendWith', 'why_bad': "The custom extension will not be registered or executed, so its behavior won't apply.", 'correct_approach': 'Always annotate the test class or specific test methods with @ExtendWith and specify the extension class.'}
{'mistake': 'Using JUnit 4 annotations or imports instead of JUnit 5', 'why_bad': "JUnit 4 does not support @ExtendWith, so the extension mechanism won't work.", 'correct_approach': 'Use JUnit 5 imports and annotations (org.junit.jupiter.api) for extensions.'}
Implementing the extension interface incorrectly or missing required methods
{'mistake': 'Placing @ExtendWith on a method but expecting it to apply to other methods', 'why_bad': "The extension applies only to the annotated method, so other tests won't use it.", 'correct_approach': 'Annotate the whole class if the extension should apply to all test methods.'}
Bonus Challenge

Now add data-driven testing with 3 different inputs to the test method using @ParameterizedTest and @ValueSource

Show Hint

Practice

(1/5)
1. What is the primary purpose of the @ExtendWith annotation in JUnit 5?
easy
A. To mark a method as a test case
B. To disable a test method temporarily
C. To register extensions that add extra behavior to tests
D. To specify the order of test execution

Solution

  1. Step 1: Understand the role of @ExtendWith

    This annotation is used to register extensions that can add behavior before, after, or around tests.
  2. Step 2: Compare with other annotations

    Other annotations like @Test mark test methods, but @ExtendWith is specifically for extensions.
  3. Final Answer:

    To register extensions that add extra behavior to tests -> Option C
  4. Quick Check:

    @ExtendWith = register extensions [OK]
Hint: Remember: @ExtendWith adds extra test behavior [OK]
Common Mistakes:
  • Confusing @ExtendWith with @Test
  • Thinking it disables tests
  • Assuming it controls test order
2. Which of the following is the correct syntax to use @ExtendWith to register a custom extension named MyExtension.class on a test class?
easy
A. @ExtendWith(MyExtension.class) public class TestClass {}
B. @ExtendWith{MyExtension.class} public class TestClass {}
C. @ExtendWith[MyExtension.class] public class TestClass {}
D. @ExtendWith public class TestClass {}

Solution

  1. Step 1: Recall correct annotation syntax

    Annotations use parentheses with class references, like @ExtendWith(MyExtension.class).
  2. Step 2: Identify invalid syntax

    Curly braces, square brackets, or angle brackets are not valid for this annotation.
  3. Final Answer:

    @ExtendWith(MyExtension.class) public class TestClass {} -> Option A
  4. Quick Check:

    Annotation syntax uses parentheses () [OK]
Hint: Use parentheses () with class name for annotations [OK]
Common Mistakes:
  • Using curly braces {} instead of parentheses
  • Using square brackets [] or angle brackets <>
  • Omitting .class after the class name
3. Given the following code snippet, what will be printed when the test runs?
@ExtendWith(MyExtension.class)
public class SampleTest {
    @Test
    void testMethod() {
        System.out.println("Test running");
    }
}

class MyExtension implements BeforeTestExecutionCallback {
    public void beforeTestExecution(ExtensionContext context) {
        System.out.println("Before test");
    }
}
medium
A. Before test
B. Test running\nBefore test
C. Test running
D. Before test\nTest running

Solution

  1. Step 1: Understand extension behavior

    The MyExtension implements BeforeTestExecutionCallback, so it runs code before the test method.
  2. Step 2: Trace output order

    First, "Before test" prints from the extension, then "Test running" prints from the test method.
  3. Final Answer:

    Before test\nTest running -> Option D
  4. Quick Check:

    Extension beforeTestExecution runs before test method [OK]
Hint: BeforeTestExecutionCallback runs before test method [OK]
Common Mistakes:
  • Assuming extension runs after test
  • Ignoring extension output
  • Confusing output order
4. Identify the error in the following JUnit 5 test class using @ExtendWith:
@ExtendWith
public class FaultyTest {
    @Test
    void testSomething() {}
}
medium
A. @ExtendWith cannot be used on classes
B. @ExtendWith is missing the extension class argument
C. The test method must be static
D. The test method must return a value

Solution

  1. Step 1: Check @ExtendWith usage

    The annotation requires specifying which extension class to use, e.g., @ExtendWith(MyExtension.class).
  2. Step 2: Validate other options

    It is valid on classes, test methods do not need to be static or return values.
  3. Final Answer:

    @ExtendWith is missing the extension class argument -> Option B
  4. Quick Check:

    @ExtendWith needs extension class specified [OK]
Hint: Always specify extension class inside @ExtendWith() [OK]
Common Mistakes:
  • Omitting the extension class argument
  • Thinking @ExtendWith can't be on classes
  • Believing test methods must be static
5. You want to reuse a setup logic that prints "Setup done" before each test method in multiple test classes. How should you apply @ExtendWith to achieve this cleanly?
hard
A. Create a custom extension class implementing BeforeEachCallback and annotate each test class with @ExtendWith(YourExtension.class)
B. Add a static method printing "Setup done" and call it manually in each test method
C. Use @BeforeAll annotation in each test class to print "Setup done"
D. Annotate each test method with @ExtendWith(YourExtension.class) instead of the class

Solution

  1. Step 1: Identify reusable setup approach

    Implementing a custom extension with BeforeEachCallback allows running code before each test method.
  2. Step 2: Apply @ExtendWith on test classes

    Annotating test classes with @ExtendWith(YourExtension.class) reuses the setup logic cleanly across classes.
  3. Step 3: Evaluate other options

    Manually calling methods or using @BeforeAll is less reusable or runs only once per class. Annotating methods individually is repetitive.
  4. Final Answer:

    Create a custom extension class implementing BeforeEachCallback and annotate each test class with @ExtendWith(YourExtension.class) -> Option A
  5. Quick Check:

    Custom extension + @ExtendWith on class = reusable setup [OK]
Hint: Use custom extension + @ExtendWith on class for reusable setup [OK]
Common Mistakes:
  • Calling setup manually in each test
  • Using @BeforeAll for per-test setup
  • Annotating each test method instead of class
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard