Spring Boot Testing

Spring Boot Testing

Acts as a Spring Boot testing specialist that picks the right technique, such as test slices, Testcontainers, MockitoBean and AssertJ, and covers Boot 4 with Boot 3 notes.

Skill files16 files

references/

SKILL.md209 lines
1
---
2
name: spring-boot-testing
3
description: 'Expert Spring Boot testing specialist that selects the best testing techniques for your situation: test slices, Testcontainers with @ServiceConnection, Failsafe integration tests, MockitoBean, JUnit and AssertJ. Written for Spring Boot 4 with notes for Boot 3.'
4
---
5
6
# Spring Boot Testing
7
8
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.
9
10
## Compatibility: detect first
11
12
Read the project's Spring Boot version and test dependencies before writing tests, and do not upgrade them implicitly.
13
14
| | Spring Boot 3.x | Spring Boot 4.x |
15
|--|-----------------|-----------------|
16
| JUnit | 5 (Jupiter) | 6 by default (same `org.junit.jupiter.api` annotations; JUnit 5 tests keep working) |
17
| Mock beans | `@MockitoBean` / `@MockitoSpyBean` from 3.4 (Spring Framework 6.2); `@MockBean` / `@SpyBean` are deprecated | `@MockitoBean` replaces `@MockBean` (do not use the old ones) |
18
| Test starters | `spring-boot-starter-test` covers everything | modular: add `spring-boot-starter-webmvc-test`, `spring-boot-starter-data-jpa-test`, ... |
19
| Slice imports | `org.springframework.boot.test.autoconfigure...` | moved, e.g. `org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest` |
20
| Testcontainers | 1.x names | 2.x names (`testcontainers-postgresql`) |
21
22
Details: [references/sb4-migration.md](references/sb4-migration.md), [references/mockitobean.md](references/mockitobean.md).
23
24
## Core Principles
25
26
1. **Test Pyramid**: Unit (fast) > Slice (focused) > Integration (complete)
27
2. **Right Tool**: Use the narrowest slice that gives you confidence
28
3. **AssertJ Style**: Fluent, readable assertions over verbose matchers
29
4. **Modern APIs**: Prefer MockMvcTester and RestTestClient over legacy alternatives
30
31
## Which Test Slice?
32
33
| Scenario | Annotation | Reference |
34
|----------|------------|-----------|
35
| Controller + HTTP semantics | `@WebMvcTest` | [references/webmvctest.md](references/webmvctest.md) |
36
| Repository + JPA queries | `@DataJpaTest` | [references/datajpatest.md](references/datajpatest.md) |
37
| REST client + external APIs | `@RestClientTest` | [references/restclienttest.md](references/restclienttest.md) |
38
| JSON (de)serialization | `@JsonTest` | [references/test-slices-overview.md](references/test-slices-overview.md) |
39
| Full application | `@SpringBootTest` | [references/test-slices-overview.md](references/test-slices-overview.md) |
40
41
## Test Slices Reference
42
43
- [references/test-slices-overview.md](references/test-slices-overview.md) - Decision matrix and comparison
44
- [references/webmvctest.md](references/webmvctest.md) - Web layer with MockMvc
45
- [references/datajpatest.md](references/datajpatest.md) - Data layer with Testcontainers
46
- [references/restclienttest.md](references/restclienttest.md) - REST client testing
47
48
## Testing Tools Reference
49
50
- [references/mockmvc-tester.md](references/mockmvc-tester.md) - AssertJ-style MockMvc (3.2+)
51
- [references/mockmvc-classic.md](references/mockmvc-classic.md) - Traditional MockMvc (pre-3.2)
52
- [references/resttestclient.md](references/resttestclient.md) - Spring Boot 4+ REST client
53
- [references/mockitobean.md](references/mockitobean.md) - Mocking dependencies
54
55
## Assertion Libraries
56
57
- [references/assertj-basics.md](references/assertj-basics.md) - Scalars, strings, booleans, dates
58
- [references/assertj-collections.md](references/assertj-collections.md) - Lists, Sets, Maps, arrays
59
60
## Testcontainers and integration tests
61
62
- [references/testcontainers-jdbc.md](references/testcontainers-jdbc.md) - `@ServiceConnection` quickstart, PostgreSQL, MySQL, etc.
63
- [references/failsafe-integration-tests.md](references/failsafe-integration-tests.md) - `*IT` classes silently skipped unless Failsafe is bound; run `./mvnw verify`
64
65
> **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`.
66
67
## Test Data Generation
68
69
- [references/instancio.md](references/instancio.md) - Generate complex test objects (3+ properties)
70
71
## Performance & Migration
72
73
- [references/context-caching.md](references/context-caching.md) - Speed up test suites
74
- [references/sb4-migration.md](references/sb4-migration.md) - Spring Boot 4.0 changes
75
76
## Quick Decision Tree
77
78
```
79
Testing a controller endpoint?
80
Yes → @WebMvcTest with MockMvcTester
81
82
Testing repository queries?
83
Yes → @DataJpaTest with Testcontainers (real DB)
84
85
Testing business logic in service?
86
Yes → Plain JUnit + Mockito (no Spring context)
87
88
Testing external API client?
89
Yes → @RestClientTest with MockRestServiceServer
90
91
Testing JSON mapping?
92
Yes → @JsonTest
93
94
Need full integration test?
95
Yes → @SpringBootTest with minimal context config
96
```
97
98
## Spring Boot 4 Highlights
99
100
- **RestTestClient**: Modern alternative to TestRestTemplate
101
- **@MockitoBean**: Replaces @MockBean (deprecated)
102
- **MockMvcTester**: AssertJ-style assertions for web tests
103
- **Modular starters**: Technology-specific test starters
104
- **Context pausing**: Automatic pausing of cached contexts (Spring Framework 7)
105
106
## Testing Best Practices
107
108
### Code Complexity Assessment
109
110
When a method or class is too complex to test effectively:
111
112
1. **Analyze complexity** - If you need more than 5-7 test cases to cover a single method, it's likely too complex
113
2. **Recommend refactoring** - Suggest breaking the code into smaller, focused functions
114
3. **User decision** - If the user agrees to refactor, help identify extraction points
115
4. **Proceed if needed** - If the user decides to continue with the complex code, implement tests despite the difficulty
116
117
**Example of refactoring recommendation:**
118
```java
119
// Before: Complex method hard to test
120
public Order processOrder(OrderRequest request) {
121
// Validation, discount calculation, payment, inventory, notification...
122
// 50+ lines of mixed concerns
123
}
124
125
// After: Refactored into testable units
126
public Order processOrder(OrderRequest request) {
127
validateOrder(request);
128
var order = createOrder(request);
129
applyDiscount(order);
130
processPayment(order);
131
updateInventory(order);
132
sendNotification(order);
133
return order;
134
}
135
```
136
137
### Avoid Code Redundancy
138
139
Create helper methods for commonly used objects and mock setup to enhance readability and maintainability.
140
141
### Test Organization with @DisplayName
142
143
Use descriptive display names to clarify test intent:
144
145
```java
146
@Test
147
@DisplayName("Should calculate discount for VIP customer")
148
void shouldCalculateDiscountForVip() { }
149
150
@Test
151
@DisplayName("Should reject order when customer has insufficient credit")
152
void shouldRejectOrderForInsufficientCredit() { }
153
```
154
155
### Test Coverage Order
156
157
Always structure tests in this order:
158
159
1. **Main scenario** - The happy path, most common use case
160
2. **Other paths** - Alternative valid scenarios, edge cases
161
3. **Exceptions/Errors** - Invalid inputs, error conditions, failure modes
162
163
### Test Production Scenarios
164
165
Write tests with real production scenarios in mind. This makes tests more relatable and helps understand code behavior in actual production cases.
166
167
### Test Coverage Goals
168
169
Aim for 80% code coverage as a practical balance between quality and effort. Higher coverage is beneficial but not the only goal.
170
171
Use Jacoco maven plugin for coverage reporting and tracking.
172
173
174
**Coverage Rules:**
175
- 80+% coverage minimum
176
- Focus on meaningful assertions, not just execution
177
178
**What to Prioritize:**
179
1. Business-critical paths (payment processing, order validation)
180
2. Complex algorithms (pricing, discount calculations)
181
3. Error handling (exceptions, edge cases)
182
4. Integration points (external APIs, databases)
183
184
## Dependencies (Spring Boot 4)
185
186
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>.
187
188
```xml
189
<dependency>
190
<groupId>org.springframework.boot</groupId>
191
<artifactId>spring-boot-starter-test</artifactId>
192
<scope>test</scope>
193
</dependency>
194
195
<!-- For WebMvc tests -->
196
<dependency>
197
<groupId>org.springframework.boot</groupId>
198
<artifactId>spring-boot-starter-webmvc-test</artifactId>
199
<scope>test</scope>
200
</dependency>
201
202
<!-- For Testcontainers -->
203
<dependency>
204
<groupId>org.springframework.boot</groupId>
205
<artifactId>spring-boot-testcontainers</artifactId>
206
<scope>test</scope>
207
</dependency>
208
```
209

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…