Custom extensions in JUnit - Build an Automation Script
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; import org.junit.jupiter.api.extension.AfterTestExecutionCallback; import org.junit.jupiter.api.extension.ExtensionContext; import static org.junit.jupiter.api.Assertions.assertTrue; class LoggingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { @Override public void beforeTestExecution(ExtensionContext context) { System.out.println("[Extension] Starting test: " + context.getDisplayName()); } @Override public void afterTestExecution(ExtensionContext context) { System.out.println("[Extension] Finished test: " + context.getDisplayName()); } } @ExtendWith(LoggingExtension.class) public class CustomExtensionTest { @Test void simpleTest() { assertTrue(true, "True should be true"); } }
The LoggingExtension class implements two JUnit 5 extension interfaces: BeforeTestExecutionCallback and AfterTestExecutionCallback. These allow it to run code before and after each test method.
Inside beforeTestExecution, it prints a message indicating the test is starting. Inside afterTestExecution, it prints a message indicating the test finished.
The test class CustomExtensionTest uses @ExtendWith(LoggingExtension.class) to register the extension. It has one simple test method simpleTest that asserts true is true.
When running the test, the console will show the extension's log messages before and after the test method runs, confirming the extension works. The test assertion ensures the test passes.
Modify the custom extension to measure and log the duration of each test execution
Practice
@ExtendWith?Solution
Step 1: Understand the role of custom extensions
Custom extensions allow adding reusable code that hooks into the test lifecycle, such as setup or teardown actions.Step 2: Recognize the use of @ExtendWith
The annotation@ExtendWithapplies these extensions to tests so the extra code runs automatically before or after tests.Final Answer:
To add reusable code that runs before or after tests automatically -> Option DQuick Check:
Custom extensions = reusable lifecycle code [OK]
- Thinking extensions skip assertions
- Confusing extensions with Java version settings
- Assuming extensions generate reports
MyExtension to a JUnit 5 test class?Solution
Step 1: Recall the correct annotation for extensions
JUnit 5 uses@ExtendWithto apply extensions to test classes or methods.Step 2: Check the syntax for specifying the extension class
The extension class must be passed as a class literal with.class, so@ExtendWith(MyExtension.class)is correct.Final Answer:
@ExtendWith(MyExtension.class) -> Option AQuick Check:
@ExtendWith + .class = correct syntax [OK]
- Omitting .class after the extension name
- Using wrong annotation names like @UseExtension
- Passing extension name without parentheses
public class PrintExtension implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) {
System.out.println("Before test: " + context.getDisplayName());
}
}
@ExtendWith(PrintExtension.class)
public class SampleTest {
@Test
void testOne() {}
}Solution
Step 1: Understand BeforeEachCallback behavior
ThebeforeEachmethod runs before each test method and prints the test's display name.Step 2: Identify the display name for the test method
The display name is the test method name with parentheses, so it prints "Before test: testOne()".Final Answer:
Before test: testOne() -> Option AQuick Check:
beforeEach prints test method name [OK]
- Thinking it prints class name instead of method
- Assuming no output is printed
- Confusing interface implementation
public class FaultyExtension implements BeforeEachCallback {
@Override
public void beforeEach(ExtensionContext context) {
int x = 1 / 0;
}
}
@ExtendWith(FaultyExtension.class)
public class TestClass {
@Test
void testMethod() {}
}What will happen when running
testMethod?Solution
Step 1: Analyze the extension code for errors
The extension'sbeforeEachmethod divides by zero, causing an ArithmeticException at runtime.Step 2: Understand effect on test execution
Since the exception occurs before the test runs, the test fails immediately with that exception.Final Answer:
The test will fail with an ArithmeticException before running -> Option BQuick Check:
Runtime error in extension causes test failure [OK]
- Thinking division by zero causes compile error
- Assuming test passes despite extension error
- Believing test is skipped silently
Solution
Step 1: Identify lifecycle timing for setup/teardown
Setting up before all tests and closing after all tests requires hooks that run once per test class, not per test method.Step 2: Match interfaces to lifecycle events
BeforeAllCallbackruns before all tests in a class, andAfterAllCallbackruns after all tests in a class, perfect for this use case.Final Answer:
BeforeAllCallback and AfterAllCallback -> Option CQuick Check:
BeforeAll + AfterAll = class-level setup/teardown [OK]
- Using BeforeEachCallback for class-level setup
- Confusing TestInstancePostProcessor with lifecycle callbacks
- Choosing test execution callbacks instead of all callbacks
Ready to prove it?
Pass the test and this pattern moves unknown
