Testing with JUnit5
Overview
Helidon provides a JUnit5 extension that integrates CDI to support testing with Helidon MP.
The test class is added as a CDI bean to support injection and the CDI container is started lazily during test execution.
Maven Coordinates
To enable Helidon MicroProfile Testing JUnit5, add the following dependency to
your project’s pom.xml (see Managing
Dependencies).
<dependency>
<groupId>io.helidon.microprofile.testing</groupId>
<artifactId>helidon-microprofile-testing-junit5</artifactId>
<scope>test</scope>
</dependency>
Usage
Basic usage:
@AddConfig(key = "mp.config.profile", value = "otherProfile")@Configuration(profile = "otherProfile")- Using
mp.config.profileproperty and@Config(useExisting = true)
CDI Container Setup
By default, CDI discovery is enabled:
- CDI beans and extensions in the classpath are added automatically
- If disabled, the CDI beans and extensions must be added manually
beans.xml along the test classes, as it
would combine beans from all tests.Instead, you should use @AddBean to specify the beans per test or
method.CDI discovery can be disabled using @DisableDiscovery.
Disable discovery:
When disabling discovery, it can be difficult to identify the CDI extensions needed to activate the desired features.
JAXRS (Jersey) support can be added easily using @AddJaxRs.
Add JAX-RS (Jersey):
Note the following Helidon CDI extensions:
| Extension | Note |
|---|---|
ConfigCdiExtension | Add MicroProfile Config injection support |
ServerCdiExtension | Optional if using @AddJaxRs |
JaxRsCdiExtension | Optional if using @AddJaxRs |
CDI Container Afinity
By default, one CDI container is created per test class and is shared by all test methods.
However, test methods can also require a dedicated CDI container:
- By forcing a reset of the CDI container between methods
- By customizing the CDI container per test method
Reset the CDI container between methods:
Configuration
The test configuration can be set up in two exclusive ways:
- Using the "synthetic" configuration expressed with annotations (default)
- Using the "existing" configuration of the current environment
Use @Configuration to switch to the "existing" configuration.
Switch to the existing configuration:
@Configuration(useExisting = true)
@HelidonTest
class MyTest {
}
Synthetic Configuration
The "synthetic" configuration can be expressed using the following annotations:
| Type | Usage |
|---|---|
@AddConfig | Key value pair |
@AddConfigBlock | Formatted text block |
@AddConfigSource | Programmatic config source |
@Configuration | Classpath resources using |
Add a key value pair:
@AddConfig(key = "foo", value = "bar")
@HelidonTest
class MyTest {
}
Add a properties text block:
@AddConfigBlock("""
foo=bar
bob=alice
""")
@HelidonTest
class MyTest {
}
Add a YAML text block:
@AddConfigBlock(
type = "yaml",
value = """
my-test:
foo: bar
bob: alice
""")
@HelidonTest
class MyTest {
}
Add config programmatically:
@HelidonTest
class MyTest {
@AddConfigSource
static ConfigSource config() {
return MpConfigSources.create(Map.of(
"foo", "bar",
"bob", "alice"));
}
}
Add classpath resources:
@Configuration(
configSources = {
"my-test1.yaml",
"my-test2.yaml"
})
@HelidonTest
class MyTest {
}
Configuration Ordering
The ordering of the test configuration can be controlled using the mechanism defined by the MicroProfile Config specification.
Add a properties text block with ordinal:
@AddConfigBlock(
value = """
config_ordinal=120
foo=bar
""")
@HelidonTest
class MyTest {
}
The default ordering is the following
| Annotation | Ordinal |
|---|---|
@AddConfig | 1000 |
@AddConfigBlock | 900 |
@AddConfigSource | 800 |
@Configuration | 700 |
Injectable Types
Helidon provides injection support for types that reflect the current server. E.g. JAXRS client.
Here are all the built-in types that can be injected:
| Type | Usage |
|---|---|
WebTarget | A JAX-RS client configured for the current server. |
URI | A URI representing the current server |
String | A raw URI representing the current server |
ServerCdiExtensionInject a JAX-RS client for the default socket:
@HelidonTest
class MyTest {
@Inject
WebTarget target;
}
Use @Socket to specify the socket for the clients and URIs.
Inject a JAX-RS client for the admin socket:
@HelidonTest
class MyTest {
@Inject
@Socket("admin")
WebTarget target;
}
Inject a URI for the default socket:
@HelidonTest
class MyTest {
@Inject
@Socket("@default")
URI uri;
}
Get a JAX-RS client for the default socket:
@HelidonTest
class MyTest {
@Test
void testOne(WebTarget target) {
}
}
Get a URI for the default socket:
@HelidonTest
class MyTest {
@Test
void testOne(@Socket("@default") URI uri) {
}
}
The current CDI container is also available as a method
parameter.
Get the current CDI container:
@HelidonTest
class MyTest {
@Test
void testOne(SeContainer container) {
}
}
Resolve a CDI bean:
@HelidonTest
class MyTest {
@Test
void testOne(@Default MyBean myBean) {
}
}
Test Instance Lifecyle
The CDI scope used by the test instance follows the lifecyle defined by JUnit5.
The default is PER_CLASS and is enforced by @HelidonTest.
I.e. By default, the test instance is re-used between test methods.
Using per method lifecycle:
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@HelidonTest
class MyTest {
}
Using meta-annotations
Meta-annotations are supported on both test classes and test methods and can be used as a composition mechanism.
Class-level meta-annotation example:
@HelidonTest
@AddBean(FirstBean.class)
@AddBean(SecondBean.class)
@DisableDiscovery
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomMetaAnnotation {
}
@CustomMetaAnnotation
class AnnotationOnClass {
}
Method-level meta-annotation example:
@Test
@AddBean(FirstBean.class)
@AddBean(SecondBean.class)
@DisableDiscovery
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTestMethod {
}
@HelidonTest
class AnnotationOnMethod {
@MyTestMethod
void testOne() {
}
@MyTestMethod
void testTwo() {
}
}
API
Here is a brief overview of the MicroProfile testing annotations:
| Annotation | Usage |
|---|---|
@AddBean | Add a CDI bean class to the CDI container |
@AddExtension | Add a CDI extension to the CDI container |
@DisableDiscovery | Disable automated discovery of beans and extensions |
@AddJaxRs | Shorthand to add JAX-RS (Jersey) support |
@AddConfig | Define a key value pair in the "synthetic" configuration |
@AddConfigBlock | Define a formatted text block in the "synthetic" configuration |
@AddConfigSource | Add a programmatic config source to the "synthetic" configuration |
@Configuration | Switch between "synthetic" and "existing" ; Add classpath resources to the "synthetic" configuration |
@Socket | CDI qualifier to inject a JAX-RS client or URI for a named socket |
@AfterStop | Mark a static method to be executed after the container is stopped |
Examples
Config Injection
The following example demonstrates how to enable the use of
@ConfigProperty without CDI discovery.
Config Injection Example:
Request Scope
The following example demonstrates how to use @RequestScoped
with JAXRS without CDI discovery.
Request Scope Example:
Mock Support
Mocking in Helidon MP is all about replacing CDI beans with instrumented mock classes.
This can be done using CDI alternatives, however Helidon provides an annotation to make it easy.
Maven Coordinates
To enable mock mupport add the following dependency to your project’s pom.xml.
<dependency>
<groupId>io.helidon.microprofile.testing</groupId>
<artifactId>helidon-microprofile-testing-mocking</artifactId>
<scope>test</scope>
</dependency>
Usage
Use the @MockBean annotation to inject an instrumented CDI bean in
your test, and customize it in the test method.
Example
Mocking using @MockBean:
Using CDI Alternative
@Alternative can be used to replace a CDI bean with an
instrumented instance.
Mocking using CDI Alternative:
Virtual Threads
Virtual Threads pinning can be detected during tests.
A virtual thread is "pinning" when it blocks its carrier thread in a way that prevents the virtual thread scheduler from scheduling other virtual threads.
This can happen when blocking in native code, or prior to JDK24 when a blocking IO operation happens in a synchronized block.
Pinning can in some cases negatively affect application performance.
Enable pinning detection:
@HelidonTest(pinningDetection = true)
class MyTest {
}
Pinning is considered harmful when it takes longer than 20 milliseconds, that is also the default when detecting it within tests.
Pinning threshold can be changed with:
Configure pinning threshold:
When pinning is detected, the test fails with a stacktrace pointing at the culprit.