Lesson 5 of 5 · 11 min · Testing Spring applications
Testing Spring Boot services, controllers and repositories
What you will learn
- Choose the right kind of test for each Spring layer
- Unit test a service with no Spring at all
- Test a controller with
@WebMvcTest,MockMvcTesterand@MockitoBean - Test a repository with
@DataJpaTestand a real database through Testcontainers - Write a full
@SpringBootTestand know the Spring Boot 4 changes
In simple words
A Spring application has layers: web, business and data. You do not need to start the whole application to test each one. A business class can be tested as plain Java in milliseconds. A controller can be tested with a tiny slice of Spring that fakes the layers below it. A repository can be tested against a real database in a throwaway container. The whole application starts only for a few tests that check that the pieces fit together.
Words to know
- Test slice: a test that starts only one layer of the Spring application.
- MockMvc: a tool that calls controllers without starting a real web server.
- Testcontainers: a library that starts real services, such as PostgreSQL, in Docker for tests.
- Application context: the container of beans that Spring builds for a test.
Which test for which layer
| Layer | Test style | Speed | What it proves |
|---|---|---|---|
| Business logic (service, domain classes) | plain JUnit with Mockito or fakes, no Spring | milliseconds | the rules are right |
| Controllers | @WebMvcTest with MockMvcTester, services replaced by @MockitoBean |
fast (loads only the web layer) | URLs, JSON, validation, status codes, error handling, security rules |
| Repositories | @DataJpaTest with a real database (Testcontainers) |
seconds | queries, mappings, constraints |
| Whole application | @SpringBootTest with a random port or MockMvc, real beans |
slower | the parts are wired together and work end to end |
Write most tests at the bottom (plain unit tests), fewer in the middle and only a handful of @SpringBootTest tests. Starting the Spring context is the slow part: Spring caches contexts between tests with the same configuration, so keep configuration consistent and avoid unnecessary @MockitoBean variations that create new contexts.
Dependencies
spring-boot-starter-test brings JUnit, AssertJ, Mockito and Spring's test support. In Spring Boot 4, each technology also has its own test starter that includes it (spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test, spring-boot-starter-security-test for @WithMockUser). Use the generated project from start.spring.io, which adds the right ones.
Services: plain unit tests
The CheckoutService tests from the Mockito lesson need no Spring: construct with new and pass mocks or fakes, run in milliseconds, and cover most of your logic. Keep business rules out of controllers so that they can be tested this way.
Controllers: @WebMvcTest
@WebMvcTest starts Spring MVC only (controllers, advice, filters, JSON conversion), not services or repositories, so you provide those as mocks:
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; // Boot 4 package
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvcTester mvc;
@MockitoBean OrderService service;
@Test
void getReturnsTheOrderAsJson() {
given(service.get(5L)).willReturn(new OrderResponse(5, "Asha", new BigDecimal("1200.00"), "PAID"));
assertThat(mvc.get().uri("/orders/5").accept(MediaType.APPLICATION_JSON))
.hasStatusOk()
.bodyJson()
.extractingPath("$.customer").isEqualTo("Asha");
}
@Test
void unknownOrderGives404Problem() {
given(service.get(9L)).willThrow(new OrderNotFoundException(9L));
assertThat(mvc.get().uri("/orders/9"))
.hasStatus(HttpStatus.NOT_FOUND);
}
@Test
void invalidBodyGives400() {
assertThat(mvc.post().uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"customerId\": null, \"productIds\": []}"))
.hasStatus(HttpStatus.BAD_REQUEST);
verifyNoInteractions(service); // validation stopped it before the service
}
}
Notes for Spring Boot 4 (from the official reference and the migration guide):
@WebMvcTestis inorg.springframework.boot.webmvc.test.autoconfigure.@MockitoBean(and@MockitoSpyBean) replace the removed@MockBeanand@SpyBean; they come from Spring Framework (org.springframework.test.context.bean.override.mockito).MockMvcTesteris the AssertJ-style API for MVC tests (the classicMockMvcwithperform(...)andandExpect(...)also works).- The slice scans only
@Controller,@ControllerAdvice, filters,WebMvcConfigurerand similar, not your@Serviceclasses, which is why they are mocked. - Security: with Spring Security on the classpath, tests are secured by default; annotate with
@WithMockUser(roles = "ADMIN")(needsspring-boot-starter-security-test), or import your security configuration, and add.with(csrf())for POSTs when CSRF is enabled. - Test validation, error handling (the
@RestControllerAdvice) and JSON field names here: they are easy to break and easy to test at this level.
Repositories: @DataJpaTest
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; // Boot 4 package
@DataJpaTest
class OrderRepositoryTest {
@Autowired OrderRepository orders;
@Autowired CustomerRepository customers;
@Test
void findsPaidOrdersOfACustomer() {
Customer asha = customers.save(new Customer("Asha", "asha@example.com"));
orders.save(new Order(asha, new BigDecimal("1200"), OrderStatus.PAID));
orders.save(new Order(asha, new BigDecimal("800"), OrderStatus.PENDING));
assertThat(orders.findByCustomerIdAndStatus(asha.getId(), OrderStatus.PAID)).hasSize(1);
}
}
@DataJpaTest scans entities and repositories, uses an embedded database if one is on the classpath, wraps each test in a transaction that rolls back, and provides a TestEntityManager. An in-memory H2 database differs from PostgreSQL in function names, case sensitivity, JSON support and locking, so for queries that matter use the real database with Testcontainers:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) // keep my data source
@Testcontainers
class OrderRepositoryPostgresTest {
@Container
@ServiceConnection // Spring Boot wires the container's URL, user and password
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17");
...
}
@ServiceConnection (Spring Boot 3.1 and later) configures the data source from the container automatically; Docker must be available (locally and in CI). Containers start once per test class (or per JVM if shared), so the cost is acceptable for a few repository test classes.
Because @DataJpaTest rolls back, constraint checks that happen at flush time may not fire; call entityManager.flush() when testing constraint violations or @Version conflicts. The @AutoConfigureTestDatabase annotation lives in org.springframework.boot.jdbc.test.autoconfigure in Boot 4.
The whole application: @SpringBootTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
class OrderApiIntegrationTest {
@Autowired RestTestClient client;
@Test
void createThenFetchAnOrder() {
client.post().uri("/orders")
.contentType(MediaType.APPLICATION_JSON)
.body(new CreateOrderRequest(1L, List.of(1L, 2L)))
.exchange()
.expectStatus().isCreated()
.expectHeader().exists("Location");
}
}
@SpringBootTest loads the full application context. With webEnvironment = RANDOM_PORT it starts the real embedded server; the client can be RestTestClient (new in Boot 4, added with @AutoConfigureRestTestClient), TestRestTemplate (now in org.springframework.boot.resttestclient and needing the spring-boot-resttestclient dependency) or WebTestClient. The default MOCK environment uses a mock servlet, and in Boot 4 @SpringBootTest no longer auto-configures MockMvc; add @AutoConfigureMockMvc. Use these tests for a few critical journeys (create and read an order, login, payment) with a Testcontainers database, not for every rule.
Other useful test annotations: @ActiveProfiles("test") to pick application-test.properties, @TestPropertySource and @DynamicPropertySource for per-test properties, @Sql to load SQL before a test, @JsonTest for JSON serialisation of DTOs, and @TestConfiguration for extra beans.
Common mistakes
- Using
@SpringBootTestfor everything, making the suite slow. - Old annotations (
@MockBean,javaximports,spring-boot-starter-websamples) with Boot 4. - Testing the controller with a mocked service but never testing validation and error handling.
- Trusting H2 for queries that behave differently in PostgreSQL.
- A new application context for every test class because of differing
@MockitoBeansets. - Tests that depend on data left by other tests; let
@DataJpaTestroll back or clean up. - Forgetting security in
@WebMvcTestand getting 401 or 403.
Try it yourself
- Write a plain unit test for a service with Mockito, and a
@WebMvcTestfor its controller, with@MockitoBean. - Add tests for 404, a validation 400 and a successful 201 with a
Locationheader. - Write a
@DataJpaTestfor a derived query, first on H2, then on PostgreSQL with Testcontainers. - Write one
@SpringBootTestthat creates and fetches an order through the real server. - Count how long each kind of test takes and compare.
Check yourself
What does @WebMvcTest load?
Only the web layer (controllers, advice, filters, JSON conversion); services and repositories are not loaded and must be mocked with @MockitoBean.
What replaced @MockBean in Spring Boot 4?
@MockitoBean (and @MockitoSpyBean), provided by Spring Framework.
Why use Testcontainers for repository tests?
To test queries and mappings against the same database engine as production, which an embedded H2 database may not behave like.
Why keep the number of @SpringBootTest tests small?
They start the whole context and are much slower than unit and slice tests; use them for a few critical end-to-end checks.
Interview questions
How do you test a Spring REST controller?
With @WebMvcTest and MockMvc or MockMvcTester, mocking the service with @MockitoBean, asserting status codes, JSON bodies, validation errors and security behaviour without starting a server.
What is the difference between @SpringBootTest and a test slice such as @DataJpaTest?
@SpringBootTest loads the entire application context; a slice loads only the beans for one layer, so it starts faster and isolates that layer.
How do you test code that uses a database without slowing the suite?
Keep most logic in plain unit tests, use a few @DataJpaTest classes with Testcontainers for queries, share containers across tests, and roll back changes per test.
Summary
- Match tests to layers: plain unit tests for services,
@WebMvcTestfor controllers,@DataJpaTestfor repositories, a few@SpringBootTestend-to-end tests. - In Spring Boot 4 use
@MockitoBean,MockMvcTester, the new...test.autoconfigurepackages and per-technology test starters. - Use Testcontainers with
@ServiceConnectionfor real databases. - Keep most tests fast, cache contexts, and test validation, errors and security as well as the happy path.
Going deeper
- Spring Boot: Testing: the test starters, modules and annotations.
- Testing Spring Boot applications:
@SpringBootTest,@WebMvcTest,@DataJpaTest,@MockitoBean. - Spring Boot 4.0 Migration Guide: test changes in Boot 4.
- Testcontainers: real databases and services for tests.
See how much of this you can explain
A free mock interview asks you new questions on Unit testing in Java with JUnit and Mockito for Java Full Stack Developer and scores every answer, with what to fix.