Skip to main content

Testing

Cert Focus

You should know which test type to use and why.

Must Know

  • Unit tests test one class without Spring.
  • @WebMvcTest loads the MVC slice.
  • @DataJpaTest loads the JPA slice.
  • @SpringBootTest loads the full application context.
  • MockMvc tests MVC behavior without a real server.
  • @MockBean or @MockitoBean replaces a Spring bean with a Mockito mock.
  • Transactional Spring tests commonly roll back by default.
  • Testcontainers provides real infrastructure for integration tests.

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 @MockBean or @MockitoBean does?
  • 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.