From the course: Complete Guide To Java Testing with JUnit 5 & Mockito

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

Custom extensions in JUnit 5

Custom extensions in JUnit 5

- [Instructor] Custom extensions in JUnit 5 provide a powerful mechanism for extending the behavior of test classes or methods. They allow you to encapsulate reusable logic that can be applied to multiple tests, such as setup and teardown operations, conditional test execution, and more. Let's say we want to log the execution time of each test method. We can achieve this by creating a simple extension that logs the start and end times of each test method. Let's create a TimingExtension class. We'll want this class to log the start and end times, so let's create a Logger field, then we'll implement a few interfaces. BeforeTestExecutionCallback, and AfterTestExecutionCallback. These allow us to define behavior that should be executed before and after each test method. In the BeforeTestExecution method, we'll log the start time of the test method and store it in the extension context. We'll add the start time as System.currentTime in milliseconds. In the AfterTestExecution method, we'll…

Contents