Testing Spring Boot Applications
Spring Boot testing covers plain unit tests with JUnit 5 and Mockito, sliced tests like @WebMvcTest and @DataJpaTest, full @SpringBootTest integration tests, and Testcontainers for real databases. Interviewers ask which to use and why.
What you will learn
- Unit test services with JUnit 5 and Mockito
- Test controllers with @WebMvcTest and MockMvc
- Test repositories with @DataJpaTest and Testcontainers
- Know when to use @SpringBootTest
Key concepts
Unit tests
No Spring context: new the class, pass mocks to the constructor. Fastest, and constructor injection makes it easy.
Slices
@WebMvcTest loads only the web layer for one controller (mock its services with @MockitoBean, which replaces the deprecated @MockBean). @DataJpaTest loads JPA, repositories and a test database, and rolls back after each test.
@SpringBootTest
Starts the whole application context, optionally with a real server (webEnvironment = RANDOM_PORT). Slowest; use for end-to-end flows.
Testcontainers
Runs real PostgreSQL, Kafka or Redis in Docker for tests. With @ServiceConnection, Spring Boot wires the connection details automatically.
Step by step
Controller slice test
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService orders;
@Test
void rejectsInvalidQuantity() throws Exception {
mvc.perform(post("/api/orders").with(jwt())
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"productId": 1, "quantity": 0, "address": "Noida"}
"""))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0].field").value("quantity"));
}
}Examples
Repository test against real PostgreSQL
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class UserRepositoryTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:17");
@Autowired UserRepository users;
@Test
void findsByEmailIgnoringCase() {
users.save(new User("Sumit", "sumit@example.com"));
assertThat(users.findByEmailIgnoreCase("SUMIT@example.com")).isPresent();
}
}Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Write a Mockito unit test for a service that throws OrderNotFoundException.
- Test a @KafkaListener end to end with a Kafka Testcontainer.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Why are @SpringBootTest suites slow and how do you speed them up?
Each distinct context configuration starts a new application context. Keep configurations identical so Spring caches and reuses the context, prefer slices and plain unit tests, and reuse containers across tests.
Mock vs Spy?
A mock replaces every method with a stub that returns defaults unless you define behaviour. A spy wraps a real object and calls real methods unless you stub specific ones. Prefer mocks; spies often signal a class that does too much.
Summary
Unit test logic without Spring, use @WebMvcTest and @DataJpaTest slices for layers, Testcontainers for real infrastructure, and @SpringBootTest sparingly for end-to-end flows.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus