0
# TestContext Framework
1
2
The TestContext Framework is the foundation of Spring's testing support, providing ApplicationContext management, dependency injection, and transaction support for integration tests. It's designed to be testing framework-agnostic, supporting JUnit 4, JUnit 5, and TestNG.
3
4
## Capabilities
5
6
### TestContext Interface
7
8
Encapsulates the context of a test execution, providing access to the ApplicationContext and test metadata.
9
10
```java { .api }
11
/**
12
* TestContext encapsulates the context in which a test is executed,
13
* agnostic of the actual testing framework in use.
14
*/
15
public interface TestContext extends AttributeAccessor, Serializable {
16
17
/**
18
* Get the application context for this test context
19
* @return the application context (never null)
20
* @throws IllegalStateException if an error occurs while retrieving the application context
21
*/
22
ApplicationContext getApplicationContext();
23
24
/**
25
* Determine if an application context has been loaded for this test context
26
* @return true if the application context has been loaded
27
*/
28
boolean hasApplicationContext();
29
30
/**
31
* Get the test class for this test context
32
* @return the test class (never null)
33
*/
34
Class<?> getTestClass();
35
36
/**
37
* Get the current test instance for this test context
38
* Note: this is a mutable property.
39
* @return the current test instance (never null)
40
*/
41
Object getTestInstance();
42
43
/**
44
* Get the current test method for this test context
45
* Note: this is a mutable property.
46
* @return the current test method (never null)
47
*/
48
Method getTestMethod();
49
50
/**
51
* Get the exception that was thrown during execution of the test method
52
* @return the exception that was thrown, or null if no exception was thrown
53
*/
54
@Nullable
55
Throwable getTestException();
56
57
/**
58
* Call this method to signal that the application context associated with this test context is dirty
59
* and should be removed from the context cache
60
*/
61
void markApplicationContextDirty(@Nullable DirtiesContext.HierarchyMode hierarchyMode);
62
63
/**
64
* Update this test context to reflect the state of the currently executing test
65
* @param testInstance the current test instance (may be null)
66
* @param testMethod the current test method (may be null)
67
* @param testException the exception that was thrown in the test method, or null if no exception was thrown
68
*/
69
void updateState(@Nullable Object testInstance, @Nullable Method testMethod, @Nullable Throwable testException);
70
71
/**
72
* Publish the ApplicationEvent created by the given eventFactory
73
* to the application context for this test context.
74
* The ApplicationEvent will only be published if the application context is available.
75
* @param eventFactory factory for lazy creation of the ApplicationEvent
76
* @since 5.2
77
*/
78
default void publishEvent(Function<TestContext, ? extends ApplicationEvent> eventFactory);
79
80
/**
81
* Set the MethodInvoker to use.
82
* By default, this method does nothing.
83
* @param methodInvoker the MethodInvoker to use
84
* @since 6.1
85
*/
86
default void setMethodInvoker(MethodInvoker methodInvoker);
87
88
/**
89
* Get the MethodInvoker to use.
90
* By default, this method returns MethodInvoker.DEFAULT_INVOKER.
91
* @return the MethodInvoker to use
92
* @since 6.1
93
*/
94
default MethodInvoker getMethodInvoker();
95
}
96
```
97
98
### TestContextManager
99
100
The main entry point for the TestContext Framework, responsible for managing TestContext and TestExecutionListener instances.
101
102
```java { .api }
103
/**
104
* TestContextManager is the main entry point into the Spring TestContext Framework.
105
* Manages a single TestContext and signals events to each registered TestExecutionListener.
106
*/
107
public class TestContextManager {
108
109
/**
110
* Construct a new TestContextManager for the specified test class
111
* @param testClass the test class to be managed
112
*/
113
public TestContextManager(Class<?> testClass);
114
115
/**
116
* Get the TestContext managed by this TestContextManager
117
* @return the TestContext (never null)
118
*/
119
public final TestContext getTestContext();
120
121
/**
122
* Hook for pre-processing a test class before execution of any tests within the class.
123
* Should be called prior to any framework-specific before class methods.
124
* @throws Exception if an error occurs
125
*/
126
public void beforeTestClass() throws Exception;
127
128
/**
129
* Hook for preparing a test instance prior to execution of any individual test methods.
130
* Should be called immediately after instantiation of the test instance.
131
* @param testInstance the test instance to prepare
132
* @throws Exception if an error occurs while preparing the test instance
133
*/
134
public void prepareTestInstance(Object testInstance) throws Exception;
135
136
/**
137
* Hook for pre-processing a test method before execution of the actual test method.
138
* Should be called prior to any framework-specific before methods.
139
* @param testInstance the current test instance
140
* @param testMethod the test method which is about to be executed
141
* @throws Exception if an error occurs
142
*/
143
public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception;
144
145
/**
146
* Hook for pre-processing a test immediately before execution of the test method.
147
* Should be called after any framework-specific before methods.
148
* @param testInstance the current test instance
149
* @param testMethod the test method which is about to be executed
150
* @throws Exception if an error occurs
151
*/
152
public void beforeTestExecution(Object testInstance, Method testMethod) throws Exception;
153
154
/**
155
* Hook for post-processing a test immediately after execution of the test method.
156
* Should be called before any framework-specific after methods.
157
* @param testInstance the current test instance
158
* @param testMethod the test method which has just been executed
159
* @param exception the exception that was thrown during execution, or null if none
160
* @throws Exception if an error occurs
161
*/
162
public void afterTestExecution(Object testInstance, Method testMethod, @Nullable Throwable exception) throws Exception;
163
164
/**
165
* Hook for post-processing a test method after execution of the actual test method.
166
* Should be called after any framework-specific after methods.
167
* @param testInstance the current test instance
168
* @param testMethod the test method which has just been executed
169
* @param exception the exception that was thrown during test method execution or by a TestExecutionListener, or null if none
170
* @throws Exception if an error occurs
171
*/
172
public void afterTestMethod(Object testInstance, Method testMethod, @Nullable Throwable exception) throws Exception;
173
174
/**
175
* Hook for post-processing a test class after execution of all tests within the class.
176
* Should be called after any framework-specific after class methods.
177
* @throws Exception if an error occurs
178
*/
179
public void afterTestClass() throws Exception;
180
}
181
```
182
183
### TestExecutionListener Interface
184
185
Defines a listener API for reacting to test execution events published by the TestContextManager.
186
187
```java { .api }
188
/**
189
* TestExecutionListener defines a listener API for reacting to test execution events
190
* published by the TestContextManager with which the listener is registered.
191
*/
192
public interface TestExecutionListener extends Ordered {
193
194
/**
195
* Pre-processes a test class before execution of all tests within the class.
196
* @param testContext the test context for the test; never null
197
* @throws Exception allows any exception to propagate
198
*/
199
default void beforeTestClass(TestContext testContext) throws Exception {}
200
201
/**
202
* Prepares the test instance of the supplied test context.
203
* @param testContext the test context for the test; never null
204
* @throws Exception allows any exception to propagate
205
*/
206
default void prepareTestInstance(TestContext testContext) throws Exception {}
207
208
/**
209
* Pre-processes a test method before execution of the actual test method.
210
* @param testContext the test context in which the test method will be executed; never null
211
* @throws Exception allows any exception to propagate
212
*/
213
default void beforeTestMethod(TestContext testContext) throws Exception {}
214
215
/**
216
* Pre-processes a test immediately before execution of the test method in the supplied test context.
217
* @param testContext the test context in which the test method will be executed; never null
218
* @throws Exception allows any exception to propagate
219
*/
220
default void beforeTestExecution(TestContext testContext) throws Exception {}
221
222
/**
223
* Post-processes a test immediately after execution of the test method in the supplied test context.
224
* @param testContext the test context in which the test method was executed; never null
225
* @throws Exception allows any exception to propagate
226
*/
227
default void afterTestExecution(TestContext testContext) throws Exception {}
228
229
/**
230
* Post-processes a test method after execution of the actual test method.
231
* @param testContext the test context in which the test method was executed; never null
232
* @throws Exception allows any exception to propagate
233
*/
234
default void afterTestMethod(TestContext testContext) throws Exception {}
235
236
/**
237
* Post-processes a test class after execution of all tests within the class.
238
* @param testContext the test context for the test; never null
239
* @throws Exception allows any exception to propagate
240
*/
241
default void afterTestClass(TestContext testContext) throws Exception {}
242
}
243
```
244
245
### Built-in TestExecutionListeners
246
247
Spring provides several built-in TestExecutionListener implementations for common testing scenarios.
248
249
```java { .api }
250
/**
251
* TestExecutionListener that provides support for dependency injection and initialization
252
* of test instances.
253
*/
254
public class DependencyInjectionTestExecutionListener extends AbstractTestExecutionListener {
255
@Override
256
public void prepareTestInstance(TestContext testContext) throws Exception;
257
}
258
259
/**
260
* TestExecutionListener that provides support for executing tests within transactions.
261
*/
262
public class TransactionalTestExecutionListener extends AbstractTestExecutionListener {
263
@Override
264
public void beforeTestMethod(TestContext testContext) throws Exception;
265
@Override
266
public void afterTestMethod(TestContext testContext) throws Exception;
267
}
268
269
/**
270
* TestExecutionListener that processes @DirtiesContext annotations.
271
*/
272
public class DirtiesContextTestExecutionListener extends AbstractTestExecutionListener {
273
@Override
274
public void beforeTestMethod(TestContext testContext) throws Exception;
275
@Override
276
public void afterTestMethod(TestContext testContext) throws Exception;
277
@Override
278
public void afterTestClass(TestContext testContext) throws Exception;
279
}
280
281
/**
282
* TestExecutionListener that provides support for executing SQL scripts configured via @Sql.
283
*/
284
public class SqlScriptsTestExecutionListener extends AbstractTestExecutionListener {
285
@Override
286
public void beforeTestMethod(TestContext testContext) throws Exception;
287
@Override
288
public void afterTestMethod(TestContext testContext) throws Exception;
289
}
290
291
/**
292
* TestExecutionListener that provides support for ApplicationEvents published during test execution.
293
*/
294
public class ApplicationEventsTestExecutionListener extends AbstractTestExecutionListener {
295
@Override
296
public void prepareTestInstance(TestContext testContext) throws Exception;
297
@Override
298
public void beforeTestMethod(TestContext testContext) throws Exception;
299
@Override
300
public void afterTestMethod(TestContext testContext) throws Exception;
301
}
302
```
303
304
### Context Configuration
305
306
Core annotations for configuring the ApplicationContext in tests.
307
308
```java { .api }
309
/**
310
* @ContextConfiguration defines class-level metadata that is used to determine
311
* how to load and configure an ApplicationContext for integration tests.
312
*/
313
@Target(ElementType.TYPE)
314
@Retention(RetentionPolicy.RUNTIME)
315
@Documented
316
@Inherited
317
public @interface ContextConfiguration {
318
319
/**
320
* Alias for locations()
321
* @return an array of resource locations
322
*/
323
@AliasFor("locations")
324
String[] value() default {};
325
326
/**
327
* The resource locations to use for loading an ApplicationContext.
328
* @return an array of resource locations
329
*/
330
@AliasFor("value")
331
String[] locations() default {};
332
333
/**
334
* The component classes to use for loading an ApplicationContext.
335
* @return an array of component classes
336
*/
337
Class<?>[] classes() default {};
338
339
/**
340
* The application context initializer classes to use for initializing a ConfigurableApplicationContext.
341
* @return an array of ApplicationContextInitializer classes
342
*/
343
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
344
345
/**
346
* Whether or not resource locations or component classes from test superclasses should be inherited.
347
* @return true if locations should be inherited
348
*/
349
boolean inheritLocations() default true;
350
351
/**
352
* Whether or not context initializers from test superclasses should be inherited.
353
* @return true if initializers should be inherited
354
*/
355
boolean inheritInitializers() default true;
356
357
/**
358
* The type of ContextLoader to use for loading an ApplicationContext.
359
* @return the ContextLoader class
360
*/
361
Class<? extends ContextLoader> loader() default ContextLoader.class;
362
363
/**
364
* The name of the context hierarchy level represented by this configuration.
365
* @return the name of the context hierarchy level
366
*/
367
String name() default "";
368
}
369
370
/**
371
* @ContextHierarchy is a class-level annotation that is used to define a hierarchy
372
* of ApplicationContexts for integration tests.
373
*/
374
@Target(ElementType.TYPE)
375
@Retention(RetentionPolicy.RUNTIME)
376
@Documented
377
@Inherited
378
public @interface ContextHierarchy {
379
380
/**
381
* A list of @ContextConfiguration instances, each of which defines a level
382
* in the context hierarchy.
383
* @return an array of @ContextConfiguration instances
384
*/
385
ContextConfiguration[] value();
386
}
387
388
/**
389
* @ActiveProfiles is a class-level annotation that is used to declare which active bean definition
390
* profiles should be used when loading an ApplicationContext for an integration test.
391
*/
392
@Target(ElementType.TYPE)
393
@Retention(RetentionPolicy.RUNTIME)
394
@Documented
395
@Inherited
396
public @interface ActiveProfiles {
397
398
/**
399
* Alias for profiles()
400
* @return the set of active profiles
401
*/
402
@AliasFor("profiles")
403
String[] value() default {};
404
405
/**
406
* The bean definition profiles to activate.
407
* @return the set of active profiles
408
*/
409
@AliasFor("value")
410
String[] profiles() default {};
411
412
/**
413
* The type of ActiveProfilesResolver to use for resolving the active profiles.
414
* @return the ActiveProfilesResolver class
415
*/
416
Class<? extends ActiveProfilesResolver> resolver() default ActiveProfilesResolver.class;
417
418
/**
419
* Whether or not active profiles from test superclasses should be inherited.
420
* @return true if active profiles should be inherited
421
*/
422
boolean inheritProfiles() default true;
423
}
424
```
425
426
**Usage Examples:**
427
428
```java
429
import org.springframework.test.context.ContextConfiguration;
430
import org.springframework.test.context.ActiveProfiles;
431
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
432
433
// Basic configuration with Java config
434
@SpringJUnitConfig(AppConfig.class)
435
class BasicIntegrationTest {
436
@Autowired
437
private UserService userService;
438
439
@Test
440
void testUserService() {
441
// test implementation
442
}
443
}
444
445
// Configuration with XML
446
@ContextConfiguration(locations = "/test-config.xml")
447
@ExtendWith(SpringExtension.class)
448
class XmlConfigTest {
449
// test implementation
450
}
451
452
// Multiple configuration files
453
@ContextConfiguration(classes = {DatabaseConfig.class, ServiceConfig.class})
454
@ActiveProfiles({"test", "embedded"})
455
@ExtendWith(SpringExtension.class)
456
class MultiConfigTest {
457
// test implementation
458
}
459
460
// Context hierarchy for complex scenarios
461
@ContextHierarchy({
462
@ContextConfiguration(name = "parent", classes = ParentConfig.class),
463
@ContextConfiguration(name = "child", classes = ChildConfig.class)
464
})
465
@ExtendWith(SpringExtension.class)
466
class HierarchyTest {
467
// test implementation
468
}
469
```
470
471
### Context Loaders
472
473
Strategy interfaces for loading ApplicationContext instances.
474
475
```java { .api }
476
/**
477
* Strategy interface for loading an ApplicationContext for an integration test
478
* managed by the Spring TestContext Framework.
479
*/
480
public interface ContextLoader {
481
482
/**
483
* Process the given array of (potentially generic) resource locations and return
484
* an array of processed locations.
485
* @param clazz the class with which the locations are associated
486
* @param locations the unprocessed resource locations to process
487
* @return an array of processed resource locations
488
*/
489
String[] processLocations(Class<?> clazz, String... locations);
490
491
/**
492
* Load a new ApplicationContext based on the supplied resource locations.
493
* @param locations the resource locations to load
494
* @return a new application context
495
* @throws Exception if context loading failed
496
*/
497
ApplicationContext loadContext(String... locations) throws Exception;
498
}
499
500
/**
501
* Enhanced ContextLoader SPI that supplies a MergedContextConfiguration to
502
* load an ApplicationContext.
503
*/
504
public interface SmartContextLoader extends ContextLoader {
505
506
/**
507
* Load a new ApplicationContext based on the supplied MergedContextConfiguration.
508
* @param mergedConfig the merged context configuration to use to load the context
509
* @return a new application context
510
* @throws Exception if context loading failed
511
*/
512
ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception;
513
514
/**
515
* Process the ContextConfigurationAttributes for a given test class.
516
* @param configAttributes the context configuration attributes to process
517
*/
518
void processContextConfiguration(ContextConfigurationAttributes configAttributes);
519
}
520
521
/**
522
* Generic utility class for working with context loaders.
523
*/
524
public abstract class ContextLoaderUtils {
525
526
/**
527
* Resolve the ContextLoader class to use for the supplied test class.
528
* @param testClass the test class for which the ContextLoader should be resolved
529
* @return the ContextLoader class to use
530
*/
531
public static Class<? extends ContextLoader> resolveContextLoaderClass(Class<?> testClass);
532
}
533
```
534
535
## Types
536
537
```java { .api }
538
/**
539
* Holder for merged context configuration containing the merged values from
540
* all ContextConfiguration annotations in a test class hierarchy.
541
*/
542
public class MergedContextConfiguration implements Serializable {
543
544
public MergedContextConfiguration(Class<?> testClass,
545
String[] locations,
546
Class<?>[] classes,
547
Set<Class<? extends ApplicationContextInitializer<?>>> contextInitializerClasses,
548
ActiveProfilesResolver activeProfilesResolver,
549
ContextLoader contextLoader);
550
551
public Class<?> getTestClass();
552
public String[] getLocations();
553
public Class<?>[] getClasses();
554
public Set<Class<? extends ApplicationContextInitializer<?>>> getContextInitializerClasses();
555
public String[] getActiveProfiles();
556
public ContextLoader getContextLoader();
557
}
558
559
/**
560
* Encapsulates the context configuration attributes declared on a test class
561
* via @ContextConfiguration.
562
*/
563
public class ContextConfigurationAttributes {
564
565
public ContextConfigurationAttributes(Class<?> declaringClass, ContextConfiguration contextConfiguration);
566
567
public Class<?> getDeclaringClass();
568
public String[] getLocations();
569
public Class<?>[] getClasses();
570
public boolean isInheritLocations();
571
public Class<? extends ContextLoader> getContextLoaderClass();
572
}
573
574
/**
575
* Strategy interface for resolving active bean definition profiles programmatically.
576
*/
577
public interface ActiveProfilesResolver {
578
579
/**
580
* Resolve the bean definition profiles to activate for the given test class.
581
* @param testClass the test class for which profiles should be resolved
582
* @return the set of active profiles for the test class, or an empty array if no profiles are active
583
*/
584
String[] resolve(Class<?> testClass);
585
}
586
```