Cheatsheet
Testing with Spring
Key idea
Spring's *TestContext framework* manages the `ApplicationContext` of integration tests: it creates it from the configuration you declare, injects beans into the test class, **caches** it to reuse it across classes with the same configuration and applies transactions, SQL scripts, profiles and properties through annotations.
Diagram (UML)
sequenceDiagram
participant J as JUnit 5
participant E as SpringExtension
participant M as TestContextManager
participant C as Context cache
participant X as ApplicationContext
J->>E: before all (test class)
E->>M: getTestContext()
M->>C: get(key = classes + profiles + properties + …)
alt cached
C-->>M: existing context
else not cached
C->>X: create and refresh
X-->>C: stored under the key
end
M->>J: inject @Autowired fields into the test instance
J->>M: before each: @Sql, begin @Transactional
J->>J: test method
J->>M: after each: rollback (unless @Commit)
opt @DirtiesContext
M->>C: remove and close the context
endKey pieces
@ExtendWith(SpringExtension.class)+@ContextConfiguration(classes = …)=@SpringJUnitConfig(…)@SpringJUnitWebConfigfor web contexts (WebApplicationContext)@ActiveProfiles,@TestPropertySource(properties = …, locations = …)@Sql(scripts, executionPhase),@SqlConfig,@SqlGroup@Transactionalin tests (rollback by default),@Commit,@Rollback,@BeforeTransaction/@AfterTransaction@DirtiesContext(classMode, methodMode)
LeaderboardIntegrationTest.java
@SpringJUnitConfig(LeaderboardConfig.class) // = @ExtendWith(SpringExtension.class) + @ContextConfiguration
@ActiveProfiles("test") // activates the fixed clock
@TestPropertySource(properties = "leaderboard.size=2") // highest-priority properties for this test
class LeaderboardIntegrationTest {
@Autowired
LeaderboardService leaderboard; // beans injected into the test instance
// …
}Remember for the exam
- A unit test: one isolated class, mocked dependencies (Mockito), no Spring. An integration test: several real pieces together, with a Spring context
- The context is cached and reused across test classes with the same key: configuration classes, profiles, properties, initializers…
- Changing profiles or properties creates another cache entry (another context, slower)
@DirtiesContextmarks the context as dirty: it's closed and the next test gets a new one- With no classes in
@ContextConfiguration, Spring looks forstaticnested classes annotated with@Configuration @Sqlruns before each method by default, inside the test transaction if there is one@TestPropertySourcehas higher priority than every other property source
Exam traps
- A
@Transactionaltest rolls back its changes when it ends, including the@Sqlones - Too much
@DirtiesContextkills the cache and makes tests slow - A test that needs Spring to check a business rule usually means a unit test is missing
@ContextConfigurationalone isn't enough in JUnit 5: you need theSpringExtension(or@SpringJUnitConfig)