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