Testing
Cert Focus
You should know which test type to use and why.
Must Know
- Unit tests test one class without Spring.
@WebMvcTestloads the MVC slice.@DataJpaTestloads the JPA slice.@SpringBootTestloads the full application context.- MockMvc tests MVC behavior without a real server.
@MockBeanor@MockitoBeanreplaces a Spring bean with a Mockito mock.- Transactional Spring tests commonly roll back by default.
- Testcontainers provides real infrastructure for integration tests.
Direct Book Links
- Spring Boot Testing Mental Model
- Unit Testing Services
- Web Layer Testing
- Integration Testing and Final Testing Review
Exam Trap
Do not use @SpringBootTest for everything. Pick the smallest test that proves the behavior.
Self-Check
- Can I choose between unit test,
@WebMvcTest,@DataJpaTest, and@SpringBootTest? - Can I explain what MockMvc does?
- Can I explain what
@MockBeanor@MockitoBeandoes? - Can I explain why slice tests are faster and narrower?
Model Answers
Use a unit test for one class without Spring. Use @WebMvcTest for controller/MVC behavior. Use @DataJpaTest for repositories and JPA mappings. Use @SpringBootTest when the full application context or multiple layers are needed.
MockMvc performs HTTP-like requests against Spring MVC without starting a real server.
@MockBean or @MockitoBean replaces a Spring bean in the application context with a Mockito mock.
Slice tests are faster and narrower because they load only one part of the application instead of the full Spring Boot context.
Memory Sentence
Unit test equals one class; slice test equals one layer; @SpringBootTest equals full context.