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

推荐订阅源

人人都是产品经理
人人都是产品经理
Stack Overflow Blog
Stack Overflow Blog
S
SegmentFault 最新的问题
博客园 - 司徒正美
aimingoo的专栏
aimingoo的专栏
U
Unit 42
GbyAI
GbyAI
B
Blog RSS Feed
博客园 - Franky
L
LangChain Blog
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 三生石上(FineUI控件)
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
G
Google Developers Blog
Last Week in AI
Last Week in AI
阮一峰的网络日志
阮一峰的网络日志
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Apple Machine Learning Research
Apple Machine Learning Research

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