This skill provides expert guide for testing Spring Boot 4 applications with modern patterns and best practices.
| Scenario | Annotation | Reference |
|---|---|---|
| Controller + HTTP semantics | @WebMvcTest |
references/webmvctest.md |
| Repository + JPA queries | @DataJpaTest |
references/datajpatest.md |
| REST client + external APIs | @RestClientTest |
references/restclienttest.md |
| JSON (de)serialization | @JsonTest |
references/test-slices-overview.md |
| Full application | @SpringBootTest |
references/test-slices-overview.md |
Testing a controller endpoint?
Yes → @WebMvcTest with MockMvcTester
Testing repository queries?
Yes → @DataJpaTest with Testcontainers (real DB)
Testing business logic in service?
Yes → Plain JUnit + Mockito (no Spring context)
Testing external API client?
Yes → @RestClientTest with MockRestServiceServer
Testing JSON mapping?
Yes → @JsonTest
Need full integration test?
Yes → @SpringBootTest with minimal context config
When a method or class is too complex to test effectively:
Example of refactoring recommendation:
// Before: Complex method hard to test
public Order processOrder(OrderRequest request) {
// Validation, discount calculation, payment, inventory, notification...
// 50+ lines of mixed concerns
}
// After: Refactored into testable units
public Order processOrder(OrderRequest request) {
validateOrder(request);
var order = createOrder(request);
applyDiscount(order);
processPayment(order);
updateInventory(order);
sendNotification(order);
return order;
}
Create helper methods for commonly used objects and mock setup to enhance readability and maintainability.
Use descriptive display names to clarify test intent:
@Test
@DisplayName("Should calculate discount for VIP customer")
void shouldCalculateDiscountForVip() { }
@Test
@DisplayName("Should reject order when customer has insufficient credit")
void shouldRejectOrderForInsufficientCredit() { }
Always structure tests in this order:
Write tests with real production scenarios in mind. This makes tests more relatable and helps understand code behavior in actual production cases.
Aim for 80% code coverage as a practical balance between quality and effort. Higher coverage is beneficial but not the only goal.
Use Jacoco maven plugin for coverage reporting and tracking.
Coverage Rules:
What to Prioritize:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- For WebMvc tests -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc-test</artifactId>
<scope>test</scope>
</dependency>
<!-- For Testcontainers -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>