A JUnit 5 extension for parameterizing tests with MicroProfile Config.
MicroProfile Config defines a comfortable way for injecting configuration into Jakarta EE applications via CDI. As JUnit test are usually not run inside a CDI container, MicroProfile Config cannot be used in this context.
This extension supports a subset of MicroProfile Config in JUnit by providing a ParameterResolver that can resolve method parameters that are annotated with @ConfigProperty.
The parameters can be provided as system properties, environment variables and properties in src/test/resources/META-INF/microprofile-config.properties.
The actual work is delegated to the SmallRye implementation of Eclipse MicroProfile Config, https://github.com/smallrye/smallrye-config
Use this extension if you want to be able to configure your tests in various ways.
For example, you could configure the test with environment variables in a parameterized Jenkins job. During development, you could provide the values as system properties on the command line or in your IDE's run configurations.
This example shows how to declaratively inject externally defined static configuration into two parameters of a test method.
import de.hamburger_software.util.junit.microprofile.config.MicroProfileConfigExtension;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(MicroProfileConfigExtension.class)
class ConnectionTest {
@Test
void testConnection(
@ConfigProperty(name = "db.username", defaultValue = "nobody") String username,
@ConfigProperty(name = "db.password") String password) {
// username will be populated from the system property "db.username" or the environment variable
// "DB_USERNAME" or from a property in src/test/resources/META-INF/microprofile-config.properties.
// If none of these sources provides a value, the declared default of "nobody" will be used.
// In contrast, if password cannot be resolved, a ParameterResolutionException will be thrown.
}
}
Injection also works for constructor parameters and parameters of methods annotated with
@BeforeEach
,@BeforeAll
,@AfterEach
and@AfterAll
.
Add this fragment to your project's pom.xml.
<dependencies>
<dependency>
<groupId>de.hamburger-software.util</groupId>
<artifactId>junit-microprofile-config-extension</artifactId>
<version>1.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Be sure to use the latest release in the <version>
element.