Spring: The context is cached between tests

Tests sharing a configuration reuse one context. Changing the configuration - or @MockitoBean - starts a new one.

Code
@SpringBootTest                       // context A
class OneTest { }

@SpringBootTest                       // context A reused - fast
class TwoTest { }

@SpringBootTest
@TestPropertySource(properties = "app.feature=on")   // context B - new startup
class ThreeTest { }

@DirtiesContext                       // throws the context away afterwards
class FourTest { }
Output
A suite with five distinct configurations starts Spring five times.
Keeping configurations uniform is the single biggest test-speed win.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11