We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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.
-
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 ofThread.sleep()
-
Keep test contexts minimal and focused on what you’re actually testing to maintain fast execution times