惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
雷峰网
雷峰网
量子位
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
博客园 - Franky
罗磊的独立博客
宝玉的分享
宝玉的分享
博客园_首页
腾讯CDC
The GitHub Blog
The GitHub Blog
D
DataBreaches.Net
IT之家
IT之家
D
Docker
Microsoft Security Blog
Microsoft Security Blog
博客园 - 司徒正美
V
V2EX
月光博客
月光博客
N
Netflix TechBlog - Medium
爱范儿
爱范儿
I
InfoQ
P
Proofpoint News Feed

Maciej Walkowiak - Java & Spring

Blog Generating HTTP clients in Spring Boot application from OpenAPI spec PostgreSQL and UUID as primary key Dynamic Projections with Spring Data JPA Container logs with Spring Boot and Testcontainers Reified Generics in Java? Faster integration tests with reusable Testcontainers and Flyway Running one-time jobs with Quartz and Spring Boot The best way to use Testcontainers with Spring Boot Spring Boot & Flyway - clear database between integration tests What's new in Spring? Activate Maven Profile by Operating System Spring Boot with Thymeleaf and Tailwind CSS - Complete Guide How to publish a Java library to Maven Central - Complete Guide Docker Compose - waiting until containers are ready Single file Java applications with JBang Beautiful bash scripts with Gum Running Java on CRaC How to log PostgreSQL queries with Testcontainers Spring Boot 3.0 & GraalVM Native Image - not a free lunch Creating Spring Cloud Function projects with AWS SAM Loading classpath resources to String with a custom JUnit extension Creating Project Templates with Cookiecutter Spring Boot component scanning without annotations Listing Maven dependencies in Spring Boot Actuator Info endpoint Spring Cloud AWS 2.3 RC2 Released How I built vlad-cli - command line interface to Vlad Mihalcea The State of Java Relational Persistence On Choosing a Tech Stack
Auto-Registering JUnit 5 extensions
2022-07-27 · via Maciej Walkowiak - Java & Spring
Published on
  • Spring Boot

In rare cases you may want to register certain extension for each test in your test suite. A typical use case that comes to my mind is benchmarking or tracing (look JUnit OpenTelemetry Extension).

A simple but tedious approach is to decorate each test class with @ExtendWith(...). I don't think anyone would have such task especially in a project with large number of test classes. Fortunately, there is a better, less invasive way.

For the sake of example let's create an extension that will measure the time it takes to execute a test:

INFO

For the sake of simplicity I am using StopWatch class from Spring Framework to measure execution time.

java

package com.example.junit;

import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;

import org.springframework.util.StopWatch;

public class BenchmarkExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback {

    @Override
    public void beforeTestExecution(ExtensionContext context) {
        var stopWatch = new StopWatch();
        context.getStore(Namespace.create(BenchmarkExtension.class, context.getRequiredTestMethod()))
                .put("stopWatch", stopWatch);
        stopWatch.start();
    }

    @Override
    public void afterTestExecution(ExtensionContext context) {
        var testMethod = context.getRequiredTestMethod();
        var stopWatch = context.getStore(Namespace.create(BenchmarkExtension.class, testMethod))
                .get("stopWatch", StopWatch.class);
        stopWatch.stop();
        context.publishReportEntry(
                String.format("Method %s#%s executed in %d ms", context.getRequiredTestClass().getName(), testMethod.getName(),
                        stopWatch.getLastTaskTimeMillis()));
    }
}

Instead of using @ExtendWith, we will use JUnit Service Loader capabilities to register extension and then enable extension auto-detection:

  1. Create a file src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension with content:

properties

com.example.junit.BenchmarkExtension
  1. Enable extensions auto-detection in src/test/resources/junit-platform.properties:

properties

junit.jupiter.extensions.autodetection.enabled=true

Note, that this enables auto-detection for all extensions registered with service loader in your classpath.

Now, when we run tests, at the end of each test following a statement similar to this one will be printed to the console:

timestamp = 2022-07-26T18:39:56.899219, value = Method com.example.MyService#testSlowMethod executed in 137 ms

While it is good to know that such feature exists, please do not abuse it - it is good to know which extensions are loaded just by looking at the test class.

Let's stay in touch and follow me on Twitter: @maciejwalkowiak

Subscribe to RSS feed