Spring Boot "java.lang.OutOfMemoryError" during tests in CI
The test JVM ran out of heap. In Spring Boot suites this is often caused by many distinct @SpringBootTest contexts (or @DirtiesContext) accumulating in memory, plus a runner heap smaller than your laptop.
What this error means
The test task fails with "java.lang.OutOfMemoryError: Java heap space" or "Metaspace", often after a batch of integration tests, and passes locally with more RAM.
JVM
java.lang.OutOfMemoryError: Java heap space
at org.springframework.context.support.AbstractApplicationContext.refresh(...)Common causes
Too many distinct application contexts
Each unique test configuration builds a new context; without caching they pile up and exhaust the heap.
A smaller heap on the runner
The CI runner has less memory than a developer machine, so a suite that fits locally overflows in CI.
How to fix it
Raise and cap the test JVM heap
Give the test task a heap that fits the runner and fails fast on leaks.
build.gradle.kts
tasks.test {
maxHeapSize = "2g"
jvmArgs("-XX:+HeapDumpOnOutOfMemoryError")
}Reduce context churn
- Share one context across tests by keeping test configuration identical.
- Remove unnecessary
@DirtiesContextso contexts are cached and reused. - Prefer slices (
@WebMvcTest/@DataJpaTest) over full contexts.
How to prevent it
- Keep test configurations uniform so Spring caches one context.
- Use
@DirtiesContextonly when a test truly mutates the context. - Set an explicit test heap sized for the runner.
Related guides
Spring Boot @DirtiesContext rebuilding the context in CIFix slow, memory-heavy Spring Boot CI caused by @DirtiesContext - it discards the cached context and rebuilds…
Spring Boot slow context: too many @SpringBootTest instead of slices in CISpeed up Spring Boot CI where every test uses @SpringBootTest - each full context is slow to build; switch to…
Spring Boot "@SpringBootTest failed to load ApplicationContext" in CIFix "java.lang.IllegalStateException: Failed to load ApplicationContext" from @SpringBootTest in CI - the who…