Spring Framework
Testing Spring Applications: Unit Tests, TestContext and MockMvc
Intermediate6 min readUpdated
Most Spring code should be tested without Spring, and the rest with a carefully cached context. This guide shows how constructor injection keeps unit tests fast, how the Spring TestContext framework loads and reuses contexts under JUnit 5, how to test data access with transactional rollback and @Sql, how to replace beans with mocks, and how to exercise controllers through MockMvc and the AssertJ-based MockMvcTester without starting a server.
What you will learn
- Decide which tests need a Spring context and write the rest as plain JUnit 5 tests
- Load a test context with @SpringJUnitConfig, profiles and test properties, and keep it cached across classes
- Test repositories inside rolled-back transactions with seeded data from @Sql
- Replace collaborators with @MockitoBean and @TestBean without breaking context caching more than necessary
- Test MVC controllers and REST endpoints with MockMvc and MockMvcTester, including validation and error bodies
The best test of a Spring service is one that never loads Spring. Constructor injection means a service is a plain object you can build with fakes in a few lines, and those tests run in milliseconds. Spring's testing support is for the parts that genuinely depend on the framework — wiring, transactions, data access, request mapping, security — and its central problem is cost: an ApplicationContext takes seconds to build, so the whole design of the TestContext framework revolves around building as few as possible and reusing them. This guide targets Spring Framework 6.x with JUnit 5 and the spring-test module; Spring Boot's test slices are covered in the Spring Boot subject.
Level one: no container
class OrderServiceTest {
private final OrderRepository repository = mock(OrderRepository.class);
private final Mailer mailer = mock(Mailer.class);
private final OrderService service = new OrderService(repository, mailer);
@Test
void confirmSendsMailToCustomer() {
when(repository.find(42L)).thenReturn(new Order(42L, "[email protected]"));
service.confirm(42L);
verify(mailer).send("[email protected]", "Order 42 confirmed");
}
}
Nothing here is Spring-specific and that is the point. If a class cannot be tested this way — because it uses field injection, calls getBean, or reads a static ApplicationContext holder — fix the class before reaching for a container. What plain tests cannot verify is the behaviour Spring adds: that @Transactional rolls back, that @Cacheable returns the cached value, that a URL maps to the method, that the security rule denies access. Those need a context.
The TestContext framework
spring-test integrates with JUnit 5 through SpringExtension. The composed annotation @SpringJUnitConfig combines the extension with @ContextConfiguration:
@SpringJUnitConfig(classes = { PersistenceConfig.class, ServiceConfig.class })
@ActiveProfiles("test")
@TestPropertySource(properties = "app.mail.enabled=false")
class CatalogServiceIntegrationTest {
@Autowired CatalogService catalog; // field injection is acceptable in tests
@Test
void repricesAndRecordsHistory(@Autowired PriceHistoryRepository history) { // parameter injection works too
catalog.reprice("SKU-1", Money.of(12_50));
assertThat(history.forSku("SKU-1")).hasSize(1);
}
}
Use a dedicated test configuration — a @Configuration class in src/test/java that imports the production configuration and overrides the parts that need a test double, such as a Clock or an outbound gateway. Keep the number of such configurations small, for the reason explained next.
Context caching
The framework caches every context it builds, keyed by the full set of inputs: configuration classes or locations, active profiles, test property sources, context initialisers, customisers (including bean overrides) and the loader. Two test classes with identical inputs share one context across the whole JVM run; any difference creates another. A suite with fifty test classes and three configurations builds three contexts; the same suite with a different @TestPropertySource on each class builds fifty.
@DirtiesContext marks a context as unusable after the test and forces a rebuild. It is occasionally necessary — a test that mutates a singleton's state, or stops a bean — but it is more often a symptom of a test that should reset what it touched. Prefer resetting state in @AfterEach. The static properties spring.test.context.cache.maxSize and the log line Started … context help you see how many contexts a run creates.
Properties, profiles and dynamic values
@ActiveProfiles selects profile-guarded beans, @TestPropertySource adds properties with highest precedence, and @DynamicPropertySource supplies values known only at runtime — the port of a container started by Testcontainers, for instance:
@SpringJUnitConfig(PersistenceConfig.class)
@Testcontainers
class RepositoryContractTest {
@Container
static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void datasource(DynamicPropertyRegistry registry) {
registry.add("db.url", postgres::getJdbcUrl);
registry.add("db.user", postgres::getUsername);
registry.add("db.password", postgres::getPassword);
}
…
}
Testing against the real database engine rather than H2 catches dialect differences — sequences, RETURNING, JSON columns, case-sensitivity — that an in-memory substitute hides. The container is shared by all tests in the class because the field is static.
Data access tests
Add @Transactional to a test class and every test method runs in a transaction that is rolled back afterwards, so tests cannot pollute each other's data. Seed rows with @Sql:
@SpringJUnitConfig(PersistenceConfig.class)
@Transactional
class JpaProductRepositoryTest {
@Autowired ProductRepository products;
@PersistenceContext EntityManager em;
@Test
@Sql("/sql/three-products.sql") // runs in the same transaction, before the method
void findsBySku() {
assertThat(products.findBySku("SKU-2")).isPresent();
}
@Test
void savesNewProduct() {
Product saved = products.save(new Product("SKU-9", "Kettle", 2_999));
em.flush(); // force the INSERT so constraints are checked
em.clear(); // drop the first-level cache so the next read hits SQL
assertThat(products.findBySku("SKU-9")).map(Product::getName).contains("Kettle");
}
@Test
@Commit // keep the data — rarely wanted
void seedsReferenceData() { … }
}
@Sql also accepts executionPhase = AFTER_TEST_METHOD for cleanup scripts and @SqlConfig for separators and error handling. TestTransaction.flagForCommit() and TestTransaction.end() give programmatic control when a test needs to observe committed data — verifying a @TransactionalEventListener, for example, which by definition never fires in a rolled-back test.
The flush() line is not optional ceremony. With JPA, the INSERT for save is deferred until flush; if the test only asserts on the managed entity in memory, it passes even when the database would reject the row.
Replacing beans
Spring Framework 6.2 brought bean overriding into spring-test, so it no longer depends on Spring Boot:
@SpringJUnitConfig(ServiceConfig.class)
class CheckoutServiceTest {
@MockitoBean PaymentGateway gateway; // replaces the PaymentGateway bean with a Mockito mock
@MockitoSpyBean OrderRepository orders; // wraps the real bean in a spy
@Autowired CheckoutService checkout;
@Test
void declinedPaymentLeavesOrderUnpaid() {
when(gateway.charge(any())).thenReturn(PaymentResult.declined("insufficient funds"));
checkout.pay(7L);
verify(orders, never()).markPaid(7L);
}
}
@TestBean is the non-Mockito sibling: it replaces a bean with the return value of a static factory method in the test class, which is right for a hand-written fake with real behaviour. All three create a context customiser, so a test class with @MockitoBean PaymentGateway gets a different cached context from one without. Declaring the overrides in an abstract base class that related tests extend keeps the cache key identical across them.
Mock at the boundary — payment gateways, mail, remote APIs, the clock — and keep the real beans in between. A test that mocks the repository under a service that is itself mocked in the controller test has verified nothing about the wiring.
Testing controllers with MockMvc
MockMvc drives DispatcherServlet with mock servlet request and response objects. Building it from a WebApplicationContext exercises your real mappings, converters, @ControllerAdvice and interceptors:
@SpringJUnitWebConfig(WebConfig.class) // @SpringJUnitConfig + @WebAppConfiguration
class ProductControllerTest {
MockMvc mvc;
@MockitoBean ProductService products;
@BeforeEach
void setUp(WebApplicationContext wac) {
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
void returnsProductAsJson() throws Exception {
when(products.find(1L)).thenReturn(Optional.of(new Product(1L, "Kettle", 2_999)));
mvc.perform(get("/api/products/1").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Kettle"))
.andExpect(jsonPath("$.priceCents").value(2999));
}
@Test
void rejectsInvalidBodyWithProblemDetail() throws Exception {
mvc.perform(post("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name": "", "priceCents": -5}
"""))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.errors[*].field").value(containsInAnyOrder("name", "priceCents")));
}
}
MockMvcBuilders.standaloneSetup(new ProductController(products)) skips the context entirely and is the fastest way to test one controller's mapping and binding; register advice with .setControllerAdvice(new ApiExceptionHandler()). The trade-off is that standalone setup uses default MVC configuration, so custom converters or argument resolvers from your WebMvcConfigurer are absent unless you add them by hand.
MockMvcTester
Spring Framework 6.2 added MockMvcTester, an AssertJ-native front end to the same engine that removes the checked exception and the static-import soup:
MockMvcTester tester = MockMvcTester.from(wac);
assertThat(tester.get().uri("/api/products/{id}", 1).accept(MediaType.APPLICATION_JSON))
.hasStatusOk()
.hasContentTypeCompatibleWith(MediaType.APPLICATION_JSON)
.bodyJson().extractingPath("$.name").isEqualTo("Kettle");
assertThat(tester.get().uri("/api/products/999"))
.hasStatus(HttpStatus.NOT_FOUND)
.hasContentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON);
Exceptions thrown by the controller are captured as part of the result rather than propagating, so you can assert .hasFailed() and inspect the cause. Either API works; the tester is more readable for new tests, and it requires AssertJ on the test classpath.
With Spring Security present, add spring-security-test and apply springSecurity() from SecurityMockMvcConfigurers to the builder; @WithMockUser and with(jwt()) then let you test authorization rules without a login round trip.
Testing outbound HTTP
MockRestServiceServer binds to a RestClient.Builder (or RestTemplate) and replays canned responses, so a gateway class is tested against the exact JSON your partner documents:
RestClient.Builder builder = RestClient.builder().baseUrl("https://inventory.internal/api");
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
InventoryGateway gateway = new InventoryGateway(builder.build());
server.expect(requestTo("https://inventory.internal/api/stock/SKU-1"))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("""
{"sku": "SKU-1", "available": 3}
""", MediaType.APPLICATION_JSON));
assertThat(gateway.stockFor("SKU-1").available()).isEqualTo(3);
server.verify();
Common mistakes
Loading a context to test logic. If the assertion is about a calculation or a branch, a plain test is faster, clearer and does not break when configuration changes.
A different context per test class. Per-class @TestPropertySource values, ad-hoc @Imports and scattered @MockitoBeans multiply contexts. Consolidate.
Asserting on unflushed JPA state. The test passes; production fails on the constraint. Flush and clear before reading back.
@DirtiesContext as a habit. It turns a cached context into a rebuilt one for every class that carries it. Reset state instead.
Mocking everything below the class under test in a context test. You have paid for a context and verified nothing it provides. Mock only at external boundaries.
Testing security by calling the service directly. @PreAuthorize is a proxy concern; a direct call to the mocked or real object without a security context proves nothing. Use @WithMockUser against the proxied bean.
Relying on H2 for a PostgreSQL application. Dialect features, sequence behaviour and JSON operators differ. Use the real engine in a container for data-access tests.
Key takeaways
- Constructor-injected classes are tested as plain objects; reserve the Spring context for wiring, transactions, data access, web and security behaviour.
@SpringJUnitConfigloads a cached context; every difference in configuration, profiles, properties or overrides creates another, so standardise the inputs.@Transactionaltests roll back automatically;@Sqlseeds data; flush and clear before verifying JPA writes.@MockitoBean,@MockitoSpyBeanand@TestBean(6.2) replace beans at the boundaries and are part of the cache key.MockMvcandMockMvcTesterexercise real mappings, converters and advice without a server;standaloneSetupisolates one controller.MockRestServiceServerand@DynamicPropertySourcewith Testcontainers cover outbound HTTP and real databases respectively.
Sources and further reading
Frequently asked questions
- Why is my test suite slow even though each test is fast?
- Almost always context churn. Every distinct combination of configuration classes, active profiles, test properties and bean overrides creates and caches a separate ApplicationContext, and each one costs seconds. Standardise on a small number of test configurations, avoid @DirtiesContext, and put @MockitoBean declarations in a shared base class or configuration so that classes share a context. Spring logs 'Started … context' lines you can count.
- Does @Transactional on a test really roll back my JPA changes?
- Yes — the transaction is rolled back after each test method by default — but with a subtlety: Hibernate defers SQL to flush, and a rollback-only transaction may never flush, so constraint violations and mapping errors stay hidden. Call entityManager.flush() (and clear()) at the end of the test, or after the write you want to verify, so the SQL actually executes.
- What is the difference between @MockitoBean and Spring Boot's @MockBean?
- They do the same job — replace or add a bean in the test context with a Mockito mock. @MockitoBean lives in Spring Framework 6.2's spring-test module and works with any Spring test, while @MockBean came from Spring Boot and was deprecated in Boot 3.4 in favour of @MockitoBean. Both create a distinct context cache key for each combination of mocked beans.
- Should I use MockMvc or a real server with TestRestTemplate?
- MockMvc runs the DispatcherServlet in-process against mock request objects: no port, no HTTP parsing, fast, and able to reach the controller through the real handler mappings, converters and advice. It cannot test servlet filters registered outside Spring, the embedded server's configuration or HTTP-level details such as compression. Use MockMvc for controller behaviour and a small number of real-server tests for the deployment surface.