Open-Source Wikis

/

Spring Framework

/

Modules

/

spring-test

spring-projects/spring-framework

spring-test

Active contributors: Sam Brannen, Juergen Hoeller, rstoyanchev

Purpose

spring-test is the largest module in the framework by file count (~1,371 Java files). It provides the TestContext framework — Spring's caching/lifecycle infrastructure for integration tests — plus mocks for the Servlet API and reactive web stack, MockMvc (Servlet-stack controller testing), WebTestClient (reactive testing), and many smaller helpers used across the framework's own tests and applications using it.

Directory layout

spring-test/
└── src/main/java/org/springframework/
    ├── mock/                                       # Mocks for environments
    │   ├── env/                                    # MockEnvironment
    │   ├── http/                                   # MockHttpInputMessage / OutputMessage / server reactive
    │   ├── jndi/                                   # SimpleNamingContextBuilder
    │   ├── web/                                    # Servlet mocks
    │   │   ├── server/                             # reactive ServerWebExchange mocks
    │   │   ├── reactive/
    │   │   └── reactive/server/                    # MockServerHttpRequest / Response
    └── test/
        ├── annotation/                             # @DirtiesContext, @Commit, @Rollback, …
        ├── context/                                # TestContext, ContextLoader, caching
        │   ├── aot/                                # AOT-aware context loading
        │   ├── cache/                              # context cache
        │   ├── event/                              # ApplicationEvents recording
        │   ├── jdbc/                               # @Sql, @SqlConfig, @SqlMergeMode
        │   ├── junit4/                             # legacy JUnit 4 support
        │   ├── junit/jupiter/                      # JUnit 5 SpringExtension
        │   ├── support/                            # AbstractContextLoader, etc.
        │   ├── transaction/                        # transactional test support
        │   └── web/                                # @WebAppConfiguration
        ├── http/                                   # client / server test helpers
        ├── jdbc/                                   # JdbcTestUtils
        ├── json/                                   # JsonContent, BasicJsonTester (Spring Boot uses these)
        ├── util/                                   # ReflectionTestUtils, etc.
        └── web/
            ├── client/                             # MockRestServiceServer
            ├── reactive/server/                    # WebTestClient
            ├── servlet/                            # MockMvc
            │   ├── client/                         # MockMvcWebTestClient
            │   ├── htmlunit/                       # HtmlUnit + WebDriver integration
            │   ├── request/                        # request builders (get(), post(), …)
            │   └── result/                         # assertions (status, content, jsonPath, …)
            └── server/

Key abstractions

Type File Role
SpringExtension spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java JUnit 5 extension wiring the TestContext framework
@SpringJUnitConfig / @ContextConfiguration spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringJUnitConfig.java Test class → context configuration
TestContextManager spring-test/src/main/java/org/springframework/test/context/TestContextManager.java Orchestrates context loading and listeners
ContextCache spring-test/src/main/java/org/springframework/test/context/cache/ContextCache.java Caches ApplicationContext instances by config
MockMvc spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java Drives DispatcherServlet without a network
WebTestClient spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java Reactive-stack test client
MockHttpServletRequest / Response spring-test/src/main/java/org/springframework/mock/web/ Servlet API mocks
MockServerHttpRequest / Response spring-test/src/main/java/org/springframework/mock/http/server/reactive/ Reactive HTTP mocks
MockEnvironment spring-test/src/main/java/org/springframework/mock/env/MockEnvironment.java In-memory Environment
MockRestServiceServer spring-test/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java Records / asserts RestTemplate/RestClient interactions
@Sql / @SqlGroup / @SqlConfig spring-test/src/main/java/org/springframework/test/context/jdbc/ Run SQL scripts around tests

How it works

TestContext lifecycle

sequenceDiagram
    participant JUnit
    participant TCF as TestContextManager
    participant Cache as ContextCache
    participant Loader as SmartContextLoader
    participant Ctx as ApplicationContext
    JUnit->>TCF: prepareTestInstance
    TCF->>Cache: lookup by configuration
    alt cached
        Cache-->>TCF: existing context
    else not cached
        TCF->>Loader: loadContext
        Loader-->>TCF: new context
        TCF->>Cache: store
    end
    TCF->>Ctx: autowire test instance
    JUnit->>JUnit: run @BeforeEach, @Test, @AfterEach
    TCF->>TCF: notify TestExecutionListeners

Test contexts are cached by their configuration key — identical @ContextConfiguration produces a single shared context. The default cache size is 32 (spring.test.context.cache.maxSize). When the cache fills, contexts are evicted LRU.

@DirtiesContext

@DirtiesContext marks a context as polluted. The cache evicts it after the test class/method, forcing the next test to start fresh. Prefer @MockitoBean over @DirtiesContext where possible — the bean replacement keys into a different cache slot rather than reloading.

MockMvc

graph LR
    Test -->|"perform(get('/users'))"| MockMvc
    MockMvc -->|"build mock request"| MR[MockHttpServletRequest]
    MockMvc --> DS[DispatcherServlet]
    DS --> Ctrl[Controller]
    DS --> Resp[MockHttpServletResponse]
    Resp --> MockMvc
    MockMvc --> Test[(assertions: status, content, jsonPath, …)]

The dispatcher runs in-memory; no network, no Servlet container. This makes MockMvc extremely fast and the recommended way to test MVC controllers.

WebTestClient

WebTestClient is the reactive analog of MockMvc plus a real-HTTP client mode. In bound mode it talks to a RouterFunction or ApplicationContext without sockets. In connected mode it issues real HTTP to a running server.

@MockitoBean

@MockitoBean (current) and @MockBean (Spring Boot's older variant) replace beans in the ApplicationContext with Mockito mocks for a test. The bean name and type are matched; the mock is configured with default behaviors.

ApplicationEvents

Tests that need to assert which events fired can record them with @RecordApplicationEvents. Useful for verifying event-driven behavior without coupling tests to listener implementations.

TestExecutionListeners

TestExecutionListener is the SPI for hooking into test execution. Built-in listeners include:

  • DependencyInjectionTestExecutionListener — autowires the test class
  • DirtiesContextTestExecutionListener — handles @DirtiesContext
  • TransactionalTestExecutionListener — wraps test methods in a rollback transaction
  • SqlScriptsTestExecutionListener — runs @Sql scripts
  • MockitoResetTestExecutionListener — resets @MockitoBean between tests

Integration points

  • Used by every other module's test code.
  • Depends on spring-core, optionally spring-aop, spring-beans, spring-context, JUnit 5, Mockito, AssertJ, Hamcrest.
  • AOT — The TestContext framework has its own AOT processor that pre-builds context configurations for native-image tests.

Entry points for modification

  • Custom test execution listener — Implement TestExecutionListener, register via @TestExecutionListeners or META-INF/spring.factories.
  • Custom context loader — Implement SmartContextLoader for non-standard context types.
  • Extending MockMvc / WebTestClient — Both expose pluggable result handlers, request post-processors, and filters.

See also

Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.

spring-test – Spring Framework wiki | Factory