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)

Test JVMJUnit 5SpringExtensionTestContextManagercontext cachecontext #1context #2LeaderboardServicemock(ResultRepository)fran-results.sql

Key pieces

  • @ExtendWith(SpringExtension.class) + @ContextConfiguration(classes = …) = @SpringJUnitConfig(…)
  • @SpringJUnitWebConfig for web contexts (WebApplicationContext)
  • @ActiveProfiles, @TestPropertySource(properties = …, locations = …)
  • @Sql(scripts, executionPhase), @SqlConfig, @SqlGroup
  • @Transactional in 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)
  • @DirtiesContext marks the context as dirty: it's closed and the next test gets a new one
  • With no classes in @ContextConfiguration, Spring looks for static nested classes annotated with @Configuration
  • @Sql runs before each method by default, inside the test transaction if there is one
  • @TestPropertySource has higher priority than every other property source

Exam traps

  • A @Transactional test rolls back its changes when it ends, including the @Sql ones
  • Too much @DirtiesContext kills the cache and makes tests slow
  • A test that needs Spring to check a business rule usually means a unit test is missing
  • @ContextConfiguration alone isn't enough in JUnit 5: you need the SpringExtension (or @SpringJUnitConfig)

← Testing with Spring · Run it