Spring Boot testing: Zero to Hero by Daniel Garnier-Moiroux

Learn best practices for Spring Boot testing, from basic unit tests to complex integration scenarios. Covers test slices, containers, security, mocking and performance optimization.

Key takeaways
  • Use @SpringBootTest for full integration tests but be aware it creates heavyweight test contexts that are cached (32 by default)

  • Test slices like @WebMvcTest, @DataJpaTest etc. load only required parts of the application context, making tests faster and more focused

  • Leverage Spring Boot’s test auto-configuration for mock MVC, security, database access rather than configuring manually

  • AssertJ provides fluent assertions that are more readable than standard JUnit assertions or Hamcrest matchers

  • Use TestContainers for integration tests requiring real databases or other services - Spring Boot has native support for it

  • @MockBean and @SpyBean can inject Mockito mocks into the Spring context for isolating components

  • Avoid overusing test contexts with different configurations as it increases test execution time and memory usage

  • The WebTestClient provides a modern API for testing web endpoints compared to MockMvc

  • Use @DynamicPropertySource to inject dynamic properties like container ports into tests

  • Spring Security test support enables testing secured endpoints with mock users and authentication

  • For async tests, use utilities like Awaitility instead of Thread.sleep()

  • Keep test contexts minimal and focused on what you’re actually testing to maintain fast execution times