Careeroza
Testing Interview Questions
@SpringBootTest vs @WebMvcTest vs @DataJpaTest?
| Annotation | Loads | Use for |
|---|---|---|
@SpringBootTest | the full application context | integration tests (slow) |
@WebMvcTest(ProductController.class) | only the web layer + MockMvc | controller tests; services are mocked |
@DataJpaTest | only JPA, repositories, embedded DB, rolls back each test | repository / query tests |
| plain JUnit + Mockito | no Spring at all | service unit tests (fastest) |
How do you test a controller with MockMvc?
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mockMvc;
@MockitoBean ProductService productService; // Boot 3.4+; older: @MockBean
@Test
void returnsProduct() throws Exception {
when(productService.findById(1L))
.thenReturn(new ProductResponse(1L, "Redmi Note 13", new BigDecimal("15999")));
mockMvc.perform(get("/api/products/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Redmi Note 13"));
}
}@Mock vs @MockBean (@MockitoBean)?
@Mock (Mockito) creates a mock in a plain unit test, no Spring involved; inject it with @InjectMocks or a constructor. @MockBean (replaced by @MockitoBean in Spring Boot 3.4) replaces a bean in the Spring context with a mock, used in @WebMvcTest/@SpringBootTest. Changing mocked beans creates a new context, which slows the suite.
How do you write a unit test for a service?
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock ProductRepository productRepository;
@InjectMocks OrderService orderService;
@Test
void failsWhenStockIsLow() {
when(productRepository.findById(1L))
.thenReturn(Optional.of(new Product(1L, "Boat Airdopes", new BigDecimal("1299"), 2)));
assertThrows(InsufficientStockException.class, () -> orderService.placeOrder(1L, 5));
verify(productRepository, never()).save(any());
}
}How do you test against a real database?
Use Testcontainers: it starts a real MySQL/PostgreSQL in Docker for the test run. In Spring Boot 3.1+ annotate the container field with @ServiceConnection and Boot wires the datasource automatically. This catches SQL dialect differences that H2 hides.
@SpringBootTest
@Testcontainers
class OrderFlowIT {
@Container @ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
}How do you make @SpringBootTest faster?
- Prefer slice tests (
@WebMvcTest,@DataJpaTest) and plain unit tests. - Keep test configuration identical across classes so Spring reuses the cached context (avoid many different
@MockBeansets). - Use
webEnvironment = MOCKunless you really need a running server. - Reuse Testcontainers across classes (static containers).