Skip to content
javahacks.dev
Testing

How to Use SpringBootTest Without Making Tests Slow

Use SpringBootTest without slow suites: share contexts, avoid DirtiesContext, trim the context, use slices and share containers.

7 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, Jenkins, JUnit5 and Selenium logos.

A test suite that takes eleven minutes on every push is a test suite people stop running. The usual suspect in a Spring Boot project is @SpringBootTest: each test class that uses it can start the whole application, which is seconds of work, and a suite with forty such classes pays that bill forty times. The surprise is that this is rarely necessary. Spring's test framework caches application contexts and reuses them across test classes, so the suite is slow not because @SpringBootTest is slow but because something is defeating the cache. This post shows how to measure where the time goes, what creates a new context, how to share configuration so the cache works, why @DirtiesContext is expensive, how to share containers, how to trim a context, how to pick a cheaper test level and how to run in parallel. Examples use Spring Boot 4, JUnit 5 and Testcontainers.

Measure first

Do not tune from a feeling. Count how many times the application context starts in a full run. Turn on the cache logging:

src/test/resources/application-test.yamlYAML
logging:
  level:
    org.springframework.test.context.cache: DEBUG

Run the suite and search the output for the cache statistics line after each test class:

Shell
mvn -B test 2>&1 | grep -E 'Spring test ApplicationContext cache statistics|Started .* in '
Text
Spring test ApplicationContext cache statistics: [DefaultContextCache@1c2d3e size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
Started ShopApplicationTests in 4.812 seconds
Spring test ApplicationContext cache statistics: [DefaultContextCache@1c2d3e size = 7, maxSize = 32, parentContextCount = 0, hitCount = 3, missCount = 7]

missCount is the number of times a context had to be built from scratch, hitCount the number of reuses. Seven misses at about five seconds each is 35 seconds of startup, and each of the misses has a cause you can remove. A healthy suite has one or two misses and many hits. The Started ... in lines give the per-context cost. Also look at where the rest of the time goes: Surefire's report lists each class's duration, and a handful of classes usually account for most of it.

What creates a new context

The cache key is the full configuration of the context. Two test classes share a context only if everything in the key is equal: the configuration classes, the active profiles, the properties set in the test, the @MockitoBean and @MockBean declarations, the context initializers and customizers, and the web environment. Any difference makes a new context. The usual culprits:

java
@SpringBootTest(properties = "feature.x=true")        // a new key
class FeatureXTest { }

@SpringBootTest
@ActiveProfiles("integration")                        // another new key
class OrderIntegrationTest { }

@SpringBootTest
class PaymentTest {
    @MockitoBean PaymentGateway gateway;              // a mock changes the key
}

@SpringBootTest(webEnvironment = RANDOM_PORT)         // a different environment: another key
class ApiTest { }

Four test classes, four contexts, even though they test one application. Each variation is individually reasonable, and together they destroy reuse. Two more silent causes: @DirtiesContext marks the context as unusable after the class or method, forcing a rebuild, and a test that uses @TestPropertySource with a unique value or a dynamic property per class. The reference is the Spring Framework's chapter on context caching.

Share the configuration

The cure is to reduce the number of distinct keys by standardizing. Put the common setup in one place and have test classes inherit or compose it, so the key is identical:

src/test/java/dev/javahacks/support/IntegrationTest.javajava
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@Import(TestContainersConfig.class)
public @interface IntegrationTest { }

Every class annotated @IntegrationTest has the same key and shares one context. This is the pattern in writing custom JUnit composed annotations. Then handle the variations deliberately. Instead of a property on the annotation, set per-test values at runtime where the application reads them dynamically. Instead of @MockitoBean in many classes, declare the mocks you need once in a shared @TestConfiguration that all integration tests import, and reset them between tests with Mockito.reset(...) in a @BeforeEach. Keep the number of distinct combinations small: aim for a handful, and write down what each is for.

Avoid DirtiesContext

@DirtiesContext tells Spring the test changed the context in a way that cannot be undone, so the cached context is discarded and the next test class must build a new one. It is used to "fix" tests that leak state, and it makes them slow instead. Replace it with cleaning the state the test changed:

java
@BeforeEach
void clean(@Autowired JdbcClient jdbc, @Autowired CacheManager caches) {
    jdbc.sql("truncate table orders, order_line restart identity cascade").update();
    caches.getCacheNames().forEach(n -> caches.getCache(n).clear());
}

State that belongs to the application (database rows, caches, in-memory queues, scheduled-task flags) can be reset by the test; singletons holding a changed configuration cannot, and for those, isolate the test in its own class with the minimum context, accepting one extra startup. @DirtiesContext at class level costs a rebuild per class, and on a method it costs one per method, which on a class with ten tests is ten startups. Search the project: grep -rn DirtiesContext src/test. Each hit should have a reason written next to it.

Share containers

Testcontainers starts real databases and brokers, and the container, not Spring, is often the slow part: a PostgreSQL container takes a few seconds, and one per test class multiplies. Start it once for the whole run, as a static singleton, and share it:

src/test/java/dev/javahacks/support/TestContainersConfig.javajava
@TestConfiguration(proxyBeanMethods = false)
public class TestContainersConfig {

    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgres() {
        return new PostgreSQLContainer<>("postgres:17").withReuse(true);
    }
}

Because every @IntegrationTest imports the same configuration and shares one context, the container starts once. withReuse(true) with testcontainers.reuse.enable=true in ~/.testcontainers.properties keeps the container alive between runs on a developer machine, turning a multi-second start into a lookup. The development-time variant of the same idea is in Testcontainers at dev time. Clean the data between tests rather than restarting the container.

Trim the context

A context that starts in 2 seconds is better than one that starts in 6, and a lot of what starts is not needed by a given test. Three ways to shrink it.

  • Lazy initialization in tests. Beans are created only when used. Set it in the test properties: spring.main.lazy-initialization=true. The trade, hiding wiring errors, is smaller in tests because the goal of each test is narrow; see what lazy initialization really hides. Keep one test with eager initialization that proves the whole context wires.
  • Exclude auto-configurations you do not use in the test profile, such as the scheduler, the mail sender, the full security chain.
  • Disable scheduled jobs and listeners under the test profile so no background work runs during tests: spring.task.scheduling.enabled=false or a profile guard on the job.

Measure after each change with the cache log and the Started line.

Use the right level

Not every test needs a Spring context at all, and the cheapest speedup is to stop using the expensive tool where a cheap one works. A rough ladder:

LevelAnnotationStartsUse for
Plain unit testnonenothingLogic in a class with constructor-injected collaborators
Web slice@WebMvcTestMVC layer onlyController mapping, validation, status codes
Data slice@DataJpaTestJPA and a databaseRepositories and queries
JSON slice@JsonTestJackson onlySerialization shape
Full@SpringBootTestThe whole applicationA few end-to-end flows

Test slices start a fraction of the application and take well under a second to a few seconds. Use them for the bulk of controller and repository tests and keep @SpringBootTest for a small number of flows that cross layers. The slices and how to use them correctly are described in Spring Boot test slices. The testing reference is at docs.spring.io. A common ratio after cleanup: dozens of plain unit tests per slice test, and a few full tests. A pyramid, not a column of end-to-end tests.

Parallel execution

Once contexts are shared and tests are isolated, run test classes in parallel to use the CPU. JUnit 5 supports it with configuration:

src/test/resources/junit-platform.propertiesproperties
junit.jupiter.execution.parallel.enabled=true
junit.jupiter.execution.parallel.mode.default=same_thread
junit.jupiter.execution.parallel.mode.classes.default=concurrent
junit.jupiter.execution.parallel.config.strategy=fixed
junit.jupiter.execution.parallel.config.fixed.parallelism=4

This runs different classes concurrently while methods within a class stay sequential. Parallel tests share a database, so they must not interfere: isolate by using unique keys per test (UUIDs, a schema per worker) instead of truncating tables that another class is using. The surest sign you are not ready is a flaky suite; fix that before adding parallelism. Alternatively use Maven Surefire's forkCount to run classes in separate JVMs, at the cost of one context per JVM.

Quick checklist

  1. Enable the context cache log and count missCount.
  2. Introduce one composed annotation for integration tests and use it everywhere.
  3. Remove @DirtiesContext; reset state instead.
  4. Move mocks into shared configuration.
  5. Start containers once and reuse them.
  6. Replace @SpringBootTest with a slice or a plain unit test wherever possible.
  7. Turn on lazy initialization and disable schedulers in the test profile.
  8. Parallelize classes only after the suite is isolated and stable.

When this does not apply

A small project with a dozen tests does not need any of this; a few seconds of startup is fine. A test that must start a fresh application, such as one that checks startup behavior or a specific configuration, should pay for its own context. And if the slowness is in the tests themselves, a sleep, a slow query or a real network call, no amount of caching helps: look at the per-test durations before you tune the framework.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.