0
# Core Testing Framework
1
2
Core Spring Boot testing capabilities providing integration test support, context loading, and test configuration management.
3
4
## Capabilities
5
6
### @SpringBootTest Annotation
7
8
Main annotation for Spring Boot integration tests with full application context loading.
9
10
```java { .api }
11
/**
12
* Annotation for a Spring Boot test that loads the full application context
13
* @since 1.4.0
14
*/
15
@Target(ElementType.TYPE)
16
@Retention(RetentionPolicy.RUNTIME)
17
@Documented
18
@Inherited
19
@BootstrapWith(SpringBootTestContextBootstrapper.class)
20
@ExtendWith(SpringExtension.class)
21
public @interface SpringBootTest {
22
/**
23
* Properties in form key=value that should be added to the Spring Environment before the test runs
24
*/
25
String[] properties() default {};
26
27
/**
28
* Application arguments that should be passed to the application under test
29
*/
30
String[] args() default {};
31
32
/**
33
* The annotated classes to use for loading an ApplicationContext
34
*/
35
Class<?>[] classes() default {};
36
37
/**
38
* The type of web environment to create when applicable
39
*/
40
WebEnvironment webEnvironment() default WebEnvironment.MOCK;
41
42
/**
43
* Whether the application's main method should be called to start the context
44
*/
45
UseMainMethod useMainMethod() default UseMainMethod.WHEN_AVAILABLE;
46
47
/**
48
* Web environment modes for SpringBootTest
49
*/
50
enum WebEnvironment {
51
/**
52
* Loads a web ApplicationContext and provides a mock web environment
53
*/
54
MOCK(false),
55
56
/**
57
* Loads a WebServerApplicationContext and provides a real web environment listening on a random port
58
*/
59
RANDOM_PORT(true),
60
61
/**
62
* Loads a WebServerApplicationContext and provides a real web environment listening on a defined port
63
*/
64
DEFINED_PORT(true),
65
66
/**
67
* Loads a regular ApplicationContext (no web environment)
68
*/
69
NONE(false);
70
71
private final boolean embedded;
72
73
WebEnvironment(boolean embedded) {
74
this.embedded = embedded;
75
}
76
77
public boolean isEmbedded() {
78
return this.embedded;
79
}
80
}
81
82
/**
83
* Options for using the application's main method
84
*/
85
enum UseMainMethod {
86
/**
87
* Always use the main method to start the context
88
*/
89
YES,
90
91
/**
92
* Never use the main method to start the context
93
*/
94
NO,
95
96
/**
97
* Use the main method when available
98
*/
99
WHEN_AVAILABLE
100
}
101
}
102
```
103
104
**Usage Examples:**
105
106
```java
107
// Basic integration test
108
@SpringBootTest
109
class BasicIntegrationTest {
110
@Test
111
void contextLoads() {
112
// Test passes if context loads successfully
113
}
114
}
115
116
// Test with web environment
117
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
118
class WebIntegrationTest {
119
@LocalServerPort
120
int port;
121
122
@Test
123
void webContextLoads() {
124
assertThat(port).isGreaterThan(0);
125
}
126
}
127
128
// Test with custom properties
129
@SpringBootTest(properties = {
130
"app.name=test-app",
131
"debug=true"
132
})
133
class PropertyTest {
134
@Value("${app.name}")
135
String appName;
136
137
@Test
138
void propertyIsSet() {
139
assertThat(appName).isEqualTo("test-app");
140
}
141
}
142
```
143
144
### @TestConfiguration Annotation
145
146
Annotation for test-specific configuration classes.
147
148
```java { .api }
149
/**
150
* Annotation for test configuration classes that should be included in tests
151
* @since 1.4.0
152
*/
153
@Target(ElementType.TYPE)
154
@Retention(RetentionPolicy.RUNTIME)
155
@Documented
156
@Configuration
157
public @interface TestConfiguration {
158
/**
159
* Explicitly specify the value for the associated bean definition
160
*/
161
String value() default "";
162
163
/**
164
* Specify whether @Bean methods should get proxied in order to enforce bean lifecycle behavior
165
*/
166
boolean proxyBeanMethods() default true;
167
}
168
```
169
170
**Usage Examples:**
171
172
```java
173
@TestConfiguration
174
static class TestConfig {
175
@Bean
176
@Primary
177
public UserService mockUserService() {
178
return Mockito.mock(UserService.class);
179
}
180
}
181
182
@SpringBootTest
183
@Import(TestConfig.class)
184
class ConfigurationTest {
185
@Autowired
186
UserService userService;
187
188
@Test
189
void usesTestConfiguration() {
190
assertThat(userService).matches(Mockito::mockingDetails);
191
}
192
}
193
```
194
195
### Context Bootstrapping
196
197
Core classes for bootstrapping Spring Boot test contexts.
198
199
```java { .api }
200
/**
201
* TestContextBootstrapper for Spring Boot integration tests
202
*/
203
public class SpringBootTestContextBootstrapper extends DefaultTestContextBootstrapper {
204
/**
205
* Process context configuration for SpringBootTest
206
*/
207
@Override
208
protected Class<?>[] getOrFindConfigurationClasses(MergedContextConfiguration mergedConfig);
209
210
/**
211
* Get context loader for Spring Boot tests
212
*/
213
@Override
214
protected Class<? extends ContextLoader> getDefaultContextLoaderClass(Class<?> testClass);
215
}
216
217
/**
218
* ApplicationContextInitializer for Spring Boot tests
219
*/
220
public class ConfigDataApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
221
/**
222
* Initialize the application context with config data support
223
*/
224
@Override
225
public void initialize(ConfigurableApplicationContext applicationContext);
226
}
227
```
228
229
### Port Injection Annotations
230
231
Annotations for injecting server ports in web integration tests.
232
233
```java { .api }
234
/**
235
* Annotation for injecting the HTTP port that got allocated at runtime
236
* @since 1.4.0
237
*/
238
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
239
@Retention(RetentionPolicy.RUNTIME)
240
@Documented
241
@Value("${local.server.port}")
242
public @interface LocalServerPort {
243
}
244
245
/**
246
* Annotation for injecting the management port that got allocated at runtime
247
* @since 1.4.0
248
*/
249
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
250
@Retention(RetentionPolicy.RUNTIME)
251
@Documented
252
@Value("${local.management.port}")
253
public @interface LocalManagementPort {
254
}
255
256
/**
257
* Annotation for injecting the RSocket server port that got allocated at runtime
258
* @since 2.2.0
259
*/
260
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
261
@Retention(RetentionPolicy.RUNTIME)
262
@Documented
263
@Value("${local.rsocket.server.port}")
264
public @interface LocalRSocketServerPort {
265
}
266
```
267
268
**Usage Examples:**
269
270
```java
271
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
272
class PortInjectionTest {
273
@LocalServerPort
274
int serverPort;
275
276
@LocalManagementPort
277
int managementPort;
278
279
@Test
280
void portsAreInjected() {
281
assertThat(serverPort).isGreaterThan(0);
282
assertThat(managementPort).isGreaterThan(0);
283
}
284
}
285
```
286
287
### Test Component Scanning
288
289
Component scanning configuration for test classes.
290
291
```java { .api }
292
/**
293
* Annotation for components that should only be picked up during component scanning in tests
294
* @since 1.4.0
295
*/
296
@Target(ElementType.TYPE)
297
@Retention(RetentionPolicy.RUNTIME)
298
@Documented
299
@Component
300
public @interface TestComponent {
301
/**
302
* The value for the associated bean definition
303
*/
304
String value() default "";
305
}
306
```
307
308
### Test Utilities
309
310
Utility classes for test setup and configuration.
311
312
```java { .api }
313
/**
314
* Utility methods for working with ApplicationContext in tests
315
*/
316
public class ApplicationContextTestUtils {
317
/**
318
* Close an ApplicationContext and ignore any exception
319
*/
320
public static void closeQuietly(ApplicationContext context);
321
}
322
323
/**
324
* Utility for adding properties to Environment in tests
325
*/
326
public class TestPropertyValues {
327
/**
328
* Create TestPropertyValues from property strings
329
*/
330
public static TestPropertyValues of(String... pairs);
331
332
/**
333
* Apply these properties to the given environment
334
*/
335
public void applyTo(ConfigurableEnvironment environment);
336
337
/**
338
* Apply these properties to the given context
339
*/
340
public void applyTo(ConfigurableApplicationContext context);
341
342
/**
343
* Apply these properties to the given application context runner
344
*/
345
public void applyTo(ApplicationContextRunner runner);
346
}
347
```
348
349
**Usage Examples:**
350
351
```java
352
class TestUtilitiesExample {
353
@Test
354
void addPropertiesToEnvironment() {
355
ConfigurableEnvironment environment = new StandardEnvironment();
356
357
TestPropertyValues.of("app.name=test", "debug=true")
358
.applyTo(environment);
359
360
assertThat(environment.getProperty("app.name")).isEqualTo("test");
361
assertThat(environment.getProperty("debug")).isEqualTo("true");
362
}
363
}
364
```
365
366
## Common Exceptions and Error Handling
367
368
### Test Context Failures
369
370
Common exceptions that may occur during Spring Boot test execution:
371
372
**Key Exceptions:**
373
- `BeanCreationException`: Thrown when required beans cannot be instantiated
374
- `NoSuchBeanDefinitionException`: Thrown when expected beans are not found
375
- `BeanDefinitionStoreException`: Thrown when bean definitions are invalid
376
- `ApplicationContextException`: General context loading failures
377
378
**Error Handling Examples:**
379
380
```java
381
@SpringBootTest
382
class ErrorHandlingTest {
383
384
@Test
385
void handleContextLoadFailure() {
386
// This test would fail if context cannot load
387
// Common causes:
388
// - Missing required beans
389
// - Configuration conflicts
390
// - Invalid property values
391
// - Classpath issues
392
}
393
394
@Test
395
void handleMissingBeanError() {
396
// Use @MockBean to provide missing dependencies
397
// Or exclude problematic auto-configurations
398
// Example: @SpringBootTest(exclude = {DataSourceAutoConfiguration.class})
399
}
400
}
401
```
402
403
### Common Error Scenarios
404
405
1. **Context Load Failures**: Usually caused by missing dependencies or configuration conflicts
406
2. **Bean Creation Errors**: Often due to missing required properties or constructor arguments
407
3. **Property Resolution Issues**: Invalid property placeholders or missing configuration files
408
4. **Profile Activation Problems**: Incorrect profile-specific configurations
409
5. **Test Slice Conflicts**: Mixing incompatible test slice annotations