Sub topic 12
Running Tests as a Native Image
This chapter assumes you can build a Spring Boot 3 project with Maven or Gradle, and that you have read the earlier chapters on building a native executable and on runtime hints. You should be comfortable with JUnit 5 and @SpringBootTest at a basic level.
Why test in native mode
A test that passes on the JVM tells you the code is correct on the JVM. A native executable is a different runtime. It has no class loading at run time, no dynamic bytecode generation, and it only contains code the build found reachable. Some bugs show up only there:
- A class used through reflection is missing from the executable.
- A classpath resource was not included.
- A bean condition was evaluated at build time and gave a different result than you expected.
- A library creates a proxy for an interface that was not registered.
Running the test suite as a native image finds these problems in the build pipeline, before they reach production. The cost is time. A native test build compiles your tests and the application classes with native-image, which takes minutes, not seconds.
How native tests work
Native testing uses the JUnit Platform. The build tool does the following:
- Spring AOT processes the test classes as well as the main classes. For each
@SpringBootTestcontext it generates the same kind of bean definition code that it generates for the application. - The GraalVM Native Build Tools plugin collects the test classes, the JUnit Platform launcher, and the generated code into one
native-imagebuild. - The result is a native test executable. The plugin runs it, and it discovers and runs the tests using the JUnit Platform.
- Results are reported in the usual format, so your CI system sees normal test reports.
The key point is that the tests run inside the native executable. The test code itself is compiled ahead of time, so the same closed-world rules apply to it.
Running native tests with Maven
A project that inherits from spring-boot-starter-parent already defines a nativeTest profile. Run it with:
./mvnw -PnativeTest testThis needs a GraalVM JDK as the active JDK, because the build calls native-image directly. Check with java -version and native-image --version before you start.
The profile attaches the native-maven-plugin goal test to the build. That goal runs the AOT test processing, builds the test executable, and runs it. The regular Surefire tests do not run in this profile, so a green ./mvnw test and a green ./mvnw -PnativeTest test are two separate results.
If you need both in CI, run them as two steps or two jobs. The JVM run is fast and gives quick feedback. The native run is slow and can run in parallel or only on the main branch.
Running native tests with Gradle
With the org.graalvm.buildtools.native plugin applied, Gradle adds a nativeTest task:
./gradlew nativeTestThe task depends on the AOT processing task for tests, so you do not need to run anything first. Output goes to build/native/nativeTestCompile, and test reports go to build/test-results/nativeTest.
A minimal build.gradle for this looks like the following.
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.5'
id 'io.spring.dependency-management' version '1.1.6'
id 'org.graalvm.buildtools.native' version '0.10.3'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}A test worth running natively
The following test checks two things that often break in native mode: that a bean is created for the property value present at build time, and that a classpath resource can be read.
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
@SpringBootTest(properties = "app.feature.enabled=true")
class FeatureNativeTests {
@Autowired(required = false)
private FeatureConfig.FeatureService featureService;
@Test
void featureBeanIsPresent() {
assertThat(featureService).isNotNull();
}
@Test
void greetingTemplateIsPackaged() throws IOException {
ClassPathResource resource = new ClassPathResource("templates/greeting.txt");
String text = resource.getContentAsString(StandardCharsets.UTF_8);
assertThat(text).isNotBlank();
}
}This test uses FeatureConfig and the templates/greeting.txt resource from the earlier chapters. If you did not register the resource pattern with a hint, the second test fails in native mode and passes on the JVM. That difference is the reason to run native tests.
What is supported in native tests
Most Spring Boot testing features work, but not all of them. Know the limits before you convert a large suite.
| Feature | Native test support |
|---|---|
| `@SpringBootTest` with a fixed set of properties | Supported |
| `@WebMvcTest`, `@DataJpaTest` and other slice tests | Supported |
| `@MockBean` and `@SpyBean` | Supported, with some limits on mocking libraries |
| `@DynamicPropertySource` | Supported, since values are read at run time |
| `@Profile`-dependent beans activated with `@ActiveProfiles` | Supported, since the profile is known when the test context is processed |
| `@DirtiesContext` | Supported in most cases, but it recreates contexts that were AOT-processed |
| Tests that build contexts dynamically at run time | Not supported |
| Mockito inline mocking of final classes | Limited, because it needs run-time bytecode changes |
| JUnit extensions that use reflection on unregistered classes | Need hints |
If a test relies on a context that Spring could not know about at build time, it fails with a message that the test context was not found among the AOT-generated ones. Move such a test to a static configuration, or exclude it from native runs.
Excluding tests from native runs
Some tests are not meaningful in native mode, for example tests that check JVM-specific behavior. JUnit 5 lets you disable them with a condition. Spring Boot's @DisabledInAotMode annotation does this for tests that cannot be AOT-processed.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.aot.DisabledInAotMode;
@SpringBootTest
@DisabledInAotMode
class DynamicContextTests {
@Test
void usesRuntimeOnlyContextSetup() {
assertThat(System.getProperty("java.version")).isNotBlank();
}
}The test runs in a normal JVM test run and is skipped in native runs. Use this sparingly. Each skipped test is a gap in native coverage.
Feeding metadata into native tests
Native tests often need reachability metadata that the application itself does not need. For example, a test may serialize a fixture class with Jackson. The application never does this, so no hint exists for it.
You have two options:
- Add a
RuntimeHintsRegistrarin the test source tree and import it with@ImportRuntimeHintson a test configuration class. - Run the tests on the JVM with the tracing agent and place the output in
src/test/resources/META-INF/native-image.
Option 1 is more maintainable, because the hint is code that is reviewed and refactored with the test. Option 2 is faster for a one-off failure, but the generated files are long and easy to let go stale.
Reading failures
A native test run can fail in three stages. Knowing the stage tells you where to look.
| Stage | Symptom | Likely cause |
|---|---|---|
| AOT processing | Exception from `ApplicationContextAotGenerator` or a message naming a test class | A test configuration uses a feature that AOT cannot process |
| Native compile | `native-image` reports an error, often about a class initialized at build time | A class has static state that must be initialized at run time |
| Test execution | A test fails with `ClassNotFoundException`, `NoSuchMethodException`, a missing resource, or a missing proxy | Missing reachability metadata |
For execution failures, the stack trace names the missing element. Add a hint for it, rebuild, and run again. Repeat until the suite passes. Each loop costs a full native build, so fix several missing elements at once when the output shows more than one.
Resources and CI considerations
Native test builds use a lot of memory. A project with several @SpringBootTest contexts can need 8 GB or more for the compile step. On a CI runner with less memory, the build ends with an out-of-memory error from native-image, or the process is killed by the operating system.
- Give the CI job enough memory, or limit parallelism of other jobs on the same runner.
- Keep the number of distinct test contexts small. Each distinct context adds generated code to the executable.
- Cache the Maven or Gradle repository, but expect the native compile itself to run every time.
Summary of the workflow
- Keep the fast JVM test suite as your main feedback loop.
- Add a native test run in CI, using
-PnativeTeston Maven ornativeTeston Gradle. - When a native test fails, identify the stage, then add a
RuntimeHintsRegistrarfor the missing element. - Skip tests that cannot work in native mode with
@DisabledInAotMode, and keep a list of them. - Start the real native executable in a smoke test.
Exercise
A test passes with ./mvnw test but fails with ./mvnw -PnativeTest test with a MissingResourceException-style error for templates/greeting.txt. In which stage does the failure occur, what is the cause, and how do you fix it?
Show answer
The failure occurs in the test execution stage, after the native test executable was built. The resource was not included in the executable, because no hint or metadata told native-image to include it. On the JVM the file is found on the classpath, so the JVM run passes. Fix it by registering the resource with a RuntimeHintsRegistrar, for example hints.resources().registerPattern("templates/greeting.txt"), and importing it with @ImportRuntimeHints. Then rebuild and rerun the native tests.
Exercise
Why does a test that sets @SpringBootTest(properties = "app.feature.enabled=true") get a different bean set than one that sets the property to false, even in a single native test executable?
Show answer
Spring AOT processes each distinct test context separately and evaluates conditions such as @ConditionalOnProperty at build time for that context. The two tests have different property sets, so they get different generated contexts, each with its own bean set. The values are fixed when the test executable is built, so they cannot be changed at run time.