Registering Extensions

Understand how to register extensions in JUnit 5.

Overview

We’ve seen JUnit 5 extensions in previous chapters, including parameter resolvers and parameterized test argument sources. These are the built-in extensions of JUnit 5. In this chapter, we’ll discuss how to create our own extensions. JUnit 5 provides the org.junit.jupiter.api.extension.Extension interface for all extensions.

An Extension is just a marker interface. Custom extensions typically implement sub-interfaces of Extension. Implementations of Extension must provide a no-args constructor for the JUnit platform to create new instances. All extension interfaces are in the org.junit.jupiter.api.extension package.

Register the extensions

To use an extension, we must first register it to JUnit 5. JUnit 5 built-in extensions are registered automatically. Custom extensions may be registered explicitly using the @ExtendWith annotation or automatically by using Java’s service providers mechanism.

The @ExtendWith annotation

The ExtendWith annotation can be added to test classes and test methods to register extensions. The only value of @ExtendWith is the array of Class<? extends Extension> objects. An @ExtendWith is a repeatable annotation, so we can add more than one @ExtendWith annotation to register multiple extensions.

Java service provider

Extensions can also be registered using Java’s service providers mechanism with java.util.ServiceLoader. This option is good for third-party extensions. These extensions can be put into classpath and registered automatically. The extensions should meet the standard requirements for service providers. The /META-INF/services directory of the JAR file should include the org.junit.jupiter.api.extension.Extension file with the extension class name as the content.

Get hands-on with 1400+ tech skills courses.