Spring TestContext Framework for comprehensive integration testing of Spring applications
npx @tessl/cli install tessl/maven-org-springframework--spring-test@6.2.00
# Spring Test
1
2
Spring Test is the comprehensive testing framework for Spring applications, providing the TestContext Framework for integration testing, MockMvc for web layer testing, extensive mock objects, and seamless JUnit/TestNG integration. It enables developers to write robust tests with full dependency injection support and transaction management.
3
4
## Package Information
5
6
- **Package Name**: org.springframework:spring-test
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: `<dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>6.2.8</version></dependency>`
10
11
## Core Imports
12
13
```java
14
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
15
import org.springframework.test.web.servlet.MockMvc;
16
import org.springframework.test.context.TestContext;
17
import org.springframework.test.context.TestContextManager;
18
```
19
20
For specific testing frameworks:
21
22
```java
23
// JUnit Jupiter
24
import org.springframework.test.context.junit.jupiter.SpringExtension;
25
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
26
27
// MockMvc testing
28
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
29
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
30
```
31
32
## Basic Usage
33
34
```java
35
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
36
import org.springframework.beans.factory.annotation.Autowired;
37
import org.junit.jupiter.api.Test;
38
39
@SpringJUnitConfig(AppConfig.class)
40
class UserServiceIntegrationTest {
41
42
@Autowired
43
private UserService userService;
44
45
@Test
46
void shouldCreateUser() {
47
User user = new User("John", "john@example.com");
48
User savedUser = userService.save(user);
49
assertThat(savedUser.getId()).isNotNull();
50
}
51
}
52
```
53
54
Web testing example:
55
56
```java
57
import org.springframework.test.web.servlet.MockMvc;
58
import org.springframework.test.context.junit.jupiter.SpringJUnitWebConfig;
59
60
@SpringJUnitWebConfig(WebConfig.class)
61
class UserControllerTest {
62
63
@Autowired
64
private MockMvc mockMvc;
65
66
@Test
67
void shouldReturnUser() throws Exception {
68
mockMvc.perform(get("/users/1"))
69
.andExpect(status().isOk())
70
.andExpect(jsonPath("$.name").value("John"));
71
}
72
}
73
```
74
75
## Architecture
76
77
Spring Test is built around several key architectural components:
78
79
- **TestContext Framework**: Core framework providing ApplicationContext loading, dependency injection, and transaction management for tests
80
- **TestContextBootstrapper**: Bootstrap mechanism that configures the TestContext Framework based on annotations and conventions
81
- **TestExecutionListener**: Event-driven lifecycle hooks for test execution (before/after class, method, execution)
82
- **ContextLoader**: Strategy interface for loading ApplicationContext instances with various implementations for different configuration types
83
- **Mock Objects**: Comprehensive mock implementations of Servlet API, HTTP client, and reactive components
84
- **Bean Override Framework**: Modern replacement for @MockBean providing flexible bean substitution in tests
85
- **Integration Layer**: Seamless integration with JUnit Jupiter, JUnit 4, and TestNG testing frameworks
86
87
## Capabilities
88
89
### TestContext Framework
90
91
Core testing framework providing ApplicationContext management, dependency injection, and transaction support for integration tests.
92
93
```java { .api }
94
public interface TestContext {
95
ApplicationContext getApplicationContext();
96
boolean hasApplicationContext();
97
Class<?> getTestClass();
98
Object getTestInstance();
99
Method getTestMethod();
100
Throwable getTestException();
101
void markApplicationContextDirty();
102
void publishEvent(ApplicationEvent event);
103
}
104
105
public class TestContextManager {
106
public TestContextManager(Class<?> testClass);
107
public void beforeTestClass() throws Exception;
108
public void prepareTestInstance(Object testInstance) throws Exception;
109
public void beforeTestMethod(Object testInstance, Method testMethod) throws Exception;
110
public void beforeTestExecution(Object testInstance, Method testMethod) throws Exception;
111
public void afterTestExecution(Object testInstance, Method testMethod, Throwable exception) throws Exception;
112
public void afterTestMethod(Object testInstance, Method testMethod, Throwable exception) throws Exception;
113
public void afterTestClass() throws Exception;
114
}
115
```
116
117
[TestContext Framework](./testcontext-framework.md)
118
119
### Web Testing Support
120
121
MockMvc framework for testing Spring MVC controllers without starting a full HTTP server, with fluent API for request building and response assertions.
122
123
```java { .api }
124
public class MockMvc {
125
public ResultActions perform(RequestBuilder requestBuilder) throws Exception;
126
}
127
128
public class MockMvcBuilders {
129
public static DefaultMockMvcBuilder webAppContextSetup(WebApplicationContext context);
130
public static StandaloneMockMvcBuilder standaloneSetup(Object... controllers);
131
}
132
133
public interface ResultActions {
134
ResultActions andExpect(ResultMatcher matcher) throws Exception;
135
ResultActions andExpectAll(ResultMatcher... matchers) throws Exception;
136
ResultActions andDo(ResultHandler handler) throws Exception;
137
MvcResult andReturn();
138
}
139
```
140
141
[Web Testing](./web-testing.md)
142
143
### Mock Objects
144
145
Comprehensive mock implementations of Servlet API, HTTP client, and reactive server components for unit and integration testing.
146
147
```java { .api }
148
public class MockHttpServletRequest implements HttpServletRequest {
149
public void setMethod(String method);
150
public void setRequestURI(String requestURI);
151
public void addParameter(String name, String... values);
152
public void addHeader(String name, Object value);
153
public void setContent(byte[] content);
154
}
155
156
public class MockHttpServletResponse implements HttpServletResponse {
157
public int getStatus();
158
public String getContentAsString();
159
public byte[] getContentAsByteArray();
160
public String getHeader(String name);
161
public String getRedirectedUrl();
162
}
163
```
164
165
[Mock Objects](./mock-objects.md)
166
167
### Testing Annotations
168
169
Core annotations for configuring test behavior, context loading, and transaction management in Spring tests.
170
171
```java { .api }
172
@Target({ElementType.TYPE})
173
@Retention(RetentionPolicy.RUNTIME)
174
public @interface ContextConfiguration {
175
String[] value() default {};
176
String[] locations() default {};
177
Class<?>[] classes() default {};
178
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
179
boolean inheritLocations() default true;
180
boolean inheritInitializers() default true;
181
Class<? extends ContextLoader> loader() default ContextLoader.class;
182
}
183
184
@Target({ElementType.TYPE})
185
@Retention(RetentionPolicy.RUNTIME)
186
public @interface ActiveProfiles {
187
String[] value() default {};
188
String[] profiles() default {};
189
Class<? extends ActiveProfilesResolver> resolver() default ActiveProfilesResolver.class;
190
boolean inheritProfiles() default true;
191
}
192
```
193
194
[Testing Annotations](./testing-annotations.md)
195
196
### JDBC Testing Support
197
198
Database testing utilities including SQL script execution and JDBC test utilities for data-driven testing scenarios.
199
200
```java { .api }
201
@Target({ElementType.TYPE, ElementType.METHOD})
202
@Retention(RetentionPolicy.RUNTIME)
203
public @interface Sql {
204
String[] value() default {};
205
String[] scripts() default {};
206
String[] statements() default {};
207
ExecutionPhase executionPhase() default ExecutionPhase.BEFORE_TEST_METHOD;
208
SqlConfig config() default @SqlConfig;
209
}
210
211
public class JdbcTestUtils {
212
public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName);
213
public static int countRowsInTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause);
214
public static int deleteFromTables(JdbcTemplate jdbcTemplate, String... tableNames);
215
public static void executeSqlScript(JdbcTemplate jdbcTemplate, Resource resource, boolean continueOnError);
216
}
217
```
218
219
[JDBC Testing](./jdbc-testing.md)
220
221
### JUnit Integration
222
223
Seamless integration with JUnit Jupiter providing Spring-specific extensions and composite annotations for simplified test configuration.
224
225
```java { .api }
226
public class SpringExtension implements BeforeAllCallback, AfterAllCallback,
227
TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback,
228
BeforeTestExecutionCallback, AfterTestExecutionCallback, ParameterResolver {
229
}
230
231
@ExtendWith(SpringExtension.class)
232
@ContextConfiguration
233
@Target(ElementType.TYPE)
234
@Retention(RetentionPolicy.RUNTIME)
235
public @interface SpringJUnitConfig {
236
Class<?>[] value() default {};
237
Class<?>[] classes() default {};
238
String[] locations() default {};
239
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
240
}
241
242
@SpringJUnitConfig
243
@WebAppConfiguration
244
@Target(ElementType.TYPE)
245
@Retention(RetentionPolicy.RUNTIME)
246
public @interface SpringJUnitWebConfig {
247
Class<?>[] value() default {};
248
Class<?>[] classes() default {};
249
String[] locations() default {};
250
}
251
```
252
253
[JUnit Integration](./junit-integration.md)
254
255
### Bean Override Framework
256
257
Modern framework for overriding beans in Spring tests, providing unified alternatives to @MockBean with better performance and integration.
258
259
```java { .api }
260
@Target({ElementType.FIELD, ElementType.TYPE})
261
@Retention(RetentionPolicy.RUNTIME)
262
public @interface MockitoBean {
263
String value() default "";
264
String name() default "";
265
Class<?>[] types() default {};
266
String contextName() default "";
267
Class<?>[] extraInterfaces() default {};
268
Answers answers() default Answers.RETURNS_DEFAULTS;
269
boolean serializable() default false;
270
MockReset reset() default MockReset.AFTER;
271
boolean enforceOverride() default false;
272
}
273
274
@Target({ElementType.FIELD, ElementType.TYPE})
275
@Retention(RetentionPolicy.RUNTIME)
276
public @interface MockitoSpyBean {
277
String value() default "";
278
String name() default "";
279
Class<?>[] types() default {};
280
String contextName() default "";
281
MockReset reset() default MockReset.AFTER;
282
}
283
284
@Target(ElementType.FIELD)
285
@Retention(RetentionPolicy.RUNTIME)
286
public @interface TestBean {
287
String value() default "";
288
String name() default "";
289
String methodName() default "";
290
String contextName() default "";
291
boolean enforceOverride() default false;
292
}
293
294
public enum MockReset {
295
BEFORE, AFTER, NONE
296
}
297
```
298
299
[Bean Override Framework](./bean-override-framework.md)
300
301
## Types
302
303
```java { .api }
304
public interface TestExecutionListener {
305
default void beforeTestClass(TestContext testContext) throws Exception {}
306
default void prepareTestInstance(TestContext testContext) throws Exception {}
307
default void beforeTestMethod(TestContext testContext) throws Exception {}
308
default void beforeTestExecution(TestContext testContext) throws Exception {}
309
default void afterTestExecution(TestContext testContext) throws Exception {}
310
default void afterTestMethod(TestContext testContext) throws Exception {}
311
default void afterTestClass(TestContext testContext) throws Exception {}
312
}
313
314
public interface ContextLoader {
315
String[] processLocations(Class<?> clazz, String... locations);
316
ApplicationContext loadContext(String... locations) throws Exception;
317
}
318
319
public interface SmartContextLoader extends ContextLoader {
320
ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception;
321
void processContextConfiguration(ContextConfigurationAttributes configAttributes);
322
}
323
324
public enum DirtiesContext.ClassMode {
325
BEFORE_CLASS,
326
BEFORE_EACH_TEST_METHOD,
327
AFTER_EACH_TEST_METHOD,
328
AFTER_CLASS
329
}
330
331
public enum DirtiesContext.MethodMode {
332
BEFORE_METHOD,
333
AFTER_METHOD
334
}
335
336
public enum Sql.ExecutionPhase {
337
BEFORE_TEST_METHOD,
338
AFTER_TEST_METHOD,
339
BEFORE_TEST_CLASS,
340
AFTER_TEST_CLASS
341
}
342
343
/**
344
* Strategy interface for invoking test methods.
345
*/
346
@FunctionalInterface
347
public interface MethodInvoker {
348
349
/**
350
* Default MethodInvoker implementation that uses reflection.
351
*/
352
MethodInvoker DEFAULT_INVOKER = (testInstance, method, args) -> {
353
return method.invoke(testInstance, args);
354
};
355
356
/**
357
* Invoke the supplied test method on the supplied test instance with the supplied arguments.
358
* @param testInstance the test instance on which to invoke the method
359
* @param method the method to invoke
360
* @param args the arguments to pass to the method
361
* @return the value returned by the method invocation
362
* @throws Exception if method invocation fails
363
*/
364
Object invoke(Object testInstance, Method method, Object... args) throws Exception;
365
}
366
```