Testing — Unit, Integration & Slice Tests
Test-Strategien in Spring Boot
Spring Boot bietet eine Test-Hierarchie: schnell (Unit) -> mittel (Slice) -> langsam (Integration).
Lektion 31: Unit Tests mit JUnit 5
class ProductServiceTest {
private final ProductRepository repo = mock(ProductRepository.class);
private final ProductService service = new ProductService(repo);
@Test
void findById_returnsProduct() {
when(repo.findById(1L)).thenReturn(Optional.of(new Product("Laptop", 999.0)));
Product p = service.findById(1L);
assertThat(p.name()).isEqualTo("Laptop");
}
}
Kein Spring-Kontext nötig — purer JUnit 5 + Mockito. Schnell und isoliert.
Lektion 32: @SpringBootTest
@SpringBootTest
@AutoConfigureMockMvc
class ProductControllerIT {
@Autowired MockMvc mockMvc;
@Test
void getAll_returns200() throws Exception {
mockMvc.perform(get("/api/products"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("Laptop"));
}
}
Lädt den vollen ApplicationContext. Langsam, aber realistisch.
Lektion 33: @MockBean & MockMvc
@MockBean ersetzt eine Bean im Context durch einen Mock:
@SpringBootTest
class ProductControllerIT {
@MockBean ProductRepository repo;
@Autowired MockMvc mockMvc;
@Test
void create_returns201() throws Exception {
when(repo.save(any())).thenReturn(new Product(1L, "Laptop", 999.0));
mockMvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Laptop\",\"price\":999.0}"))
.andExpect(status().isCreated());
}
}
Lektion 34: Slice Tests
Slice Tests vs. @SpringBootTest
@WebMvcTest lädt nur die Web-Schicht (Controller, JSON, Validierung) — keine
Datenbank, kein Service. @DataJpaTest lädt nur JPA + eingebettete DB. Beide
sind 10x schneller als @SpringBootTest.
@WebMvcTest(ProductController.class)
class ProductControllerWebTest {
@Autowired MockMvc mockMvc;
@MockBean ProductService service;
// nur Web-Schicht, kein DB-Setup
}
Lektion 35: Test-Organisation
- Arrange-Act-Assert (AAA) Pattern
- Test-Namen beschreiben das Verhalten:
findById_returnsProduct_whenExists - Ein Assertion pro Test (oder verwandte Assertions)
Die Testpyramide — viele Unit, wenige Integration
Basis: viele Unit-Tests (Service-Logik, keine Spring-Infrastruktur, < 1 s).
Mitte: Slice-Tests (@WebMvcTest, @DataJpaTest) für Schichtgrenzen.
Spitze: wenige @SpringBootTest-Tests für den ganzen Stack. Verhältnis
etwa 70/20/10 — dann bleibt die Suite schnell.
Praxis-Szenario: CropGuard: ClaimController mit @WebMvcTest
@WebMvcTest(ClaimController.class) lädt nur die Web-Schicht. ClaimService wird per @MockBean ersetzt. Der Test assess_asFarmer_returns403 braucht zusätzlich @Import(SecurityConfig.class), weil @WebMvcTest @EnableMethodSecurity sonst nicht aktiviert.
✅ Wichtige Erkenntnisse
Haken setzen, um deinen Lernfortschritt zu markieren: