This skill provides expert guidance for testing Spring Boot applications with modern patterns and best practices. Examples target Spring Boot 4; see the compatibility note below for Boot 3.
Read the project's Spring Boot version and test dependencies before writing tests, and do not upgrade them implicitly.
| Spring Boot 3.x | Spring Boot 4.x |
|---|
JUnit | 5 (Jupiter) | 6 by default (same org.junit.jupiter.api annotations; JUnit 5 tests keep working) |
Mock beans | @MockitoBean / @MockitoSpyBean from 3.4 (Spring Framework 6.2); @MockBean / @SpyBean are deprecated
| @MockitoBean replaces @MockBean (do not use the old ones)
|
Test starters | spring-boot-starter-test covers everything
| modular: add spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test, ... |
Slice imports | org.springframework.boot.test.autoconfigure...
| moved, e.g. org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest |
Testcontainers | 1.x names | 2.x names (testcontainers-postgresql) |
Details: references/sb4-migration.md, references/mockitobean.md.
- Test Pyramid: Unit (fast) > Slice (focused) > Integration (complete)
- Right Tool: Use the narrowest slice that gives you confidence
- AssertJ Style: Fluent, readable assertions over verbose matchers
- Modern APIs: Prefer MockMvcTester and RestTestClient over legacy alternatives
Maven gotcha: Failsafe declared only in <pluginManagement> means *IT tests never run. Declare it in <build><plugins> with the integration-test and verify goals and run ./mvnw verify.
Build safety: Running the build executes code from the project, including the wrapper download, test code and every build plugin. Ask the user before the first build when the repository origin is unknown, check that the wrapper and build files come from a trusted source, and prefer a sandbox or container for repositories the user does not trust. Propose changes to build files, such as the Failsafe binding, the Jacoco maven plugin or coverage thresholds, to the user and apply them once the user approves.
Docker and images: Testcontainers needs a Docker daemon, and access to it is effectively root on the host. Prefer rootless Docker or a CI sandbox, confirm with the user before starting containers on their machine, and pin images to a specific tag from a trusted registry rather than a floating latest tag.
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
- RestTestClient: Modern alternative to TestRestTemplate
- @MockitoBean: Replaces @MockBean (deprecated)
- MockMvcTester: AssertJ-style assertions for web tests
- Modular starters: Technology-specific test starters
- Context pausing: Automatic pausing of cached contexts (Spring Framework 7)
When a method or class is too complex to test effectively:
- Analyze complexity - If you need more than 5-7 test cases to cover a single method, it's likely too complex
- Recommend refactoring - Suggest breaking the code into smaller, focused functions
- User decision - If the user agrees to refactor, help identify extraction points
- Proceed if needed - If the user decides to continue with the complex code, implement tests despite the difficulty
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:
- Main scenario - The happy path, most common use case
- Other paths - Alternative valid scenarios, edge cases
- Exceptions/Errors - Invalid inputs, error conditions, failure modes
Write tests with real production scenarios in mind. This makes tests more relatable and helps understand code behavior in actual production cases. Model those scenarios with synthetic data, such as Instancio or fake values, and keep real customer data, production endpoints and credentials out of tests and test configuration; use Testcontainers or placeholders instead.
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:
- 80% coverage as a target, not an enforced minimum unless the user asks for one
- Focus on meaningful assertions, not just execution
What to Prioritize:
- Business-critical paths (payment processing, order validation)
- Complex algorithms (pricing, discount calculations)
- Error handling (exceptions, edge cases)
- Integration points (external APIs, databases)
In Boot 4, add the technology test starter for each slice you use, as listed in the compatibility table above. Omit the version only for artifacts managed by the Spring Boot parent or BOM. For unmanaged ones, such as the Jacoco maven plugin or Instancio, pin an explicit released version and check the exact group and artifact names against the official coordinates.
See also: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html and https://docs.spring.io/spring-boot/reference/features/dev-services.html.
<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>