Migration to JUnit 5 in 10 minutes Test Time Measurement with Extensions

  • Tutorial

On the last internship of Spring 5 / JPA Enterprise (Topjava), our training project migrated from JUnit 4 to JUnit 5.2. The main migration process is quite straightforward, but there are some nuances that require manual intervention. I want to briefly talk about them and create JUnit 5 Extensions to measure the time of tests in a 10-minute video.

Extension code for measuring test time
import org.junit.jupiter.api.extension.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;
publicclassTimingExtensionimplementsBeforeTestExecutionCallback, AfterTestExecutionCallback, BeforeAllCallback, AfterAllCallback{
    privatestaticfinal Logger log = LoggerFactory.getLogger("result");
    private StopWatch stopWatch;
    @OverridepublicvoidbeforeAll(ExtensionContext ctx){
        stopWatch = new StopWatch("Execution time of " + ctx.getRequiredTestClass().getSimpleName());
    @OverridepublicvoidbeforeTestExecution(ExtensionContext ctx){
        log.info("Start stopWatch");
    @OverridepublicvoidafterTestExecution(ExtensionContext ctx){
        log.info("stop stopWatch");
    @OverridepublicvoidafterAll(ExtensionContext ctx){
        log.info('\n' + stopWatch.prettyPrint() + '\n');

Useful links:

Thanks for attention!

I hope that if JUnit 4 is used on your project and you have not migrated to JUnit 5 yet, this little video will inspire you. And also on the use of JUnit 5 in your new projects.

Also popular now: