Testing with Spring Boot
- Key idea
- Spring Boot adds two tools on top of the TestContext: `@SpringBootTest` loads the whole application (finding your `@SpringBootApplication`), and *test slices* (`@WebMvcTest`, `@DataJpaTest`, `@JdbcTest`, `@JsonTest`, `@RestClientTest`…) load just one layer. `@MockitoBean` replaces a context bean with a Mockito mock.
- In the box
- To test one rule of the membership controller, the whole application was started, real bank gateway included. Pick the right test, @SpringBootTest or slices like @WebMvcTest, replace beans with @MockitoBean and test with MockMvc or a real server.
JUnit calls renew("Ana") on MembershipService, which calls charge() on the real bank gateway, highlighted in red, and fails.
Inside the test context, JUnit fires perform(post) with MockMvc; the context and MockMvc are highlighted.
The request goes through the real MockMvc, controller and service up to the gateway, which is now a @MockitoBean, highlighted, answering true.
Only MockMvc and MembershipController, highlighted, are in the test context; JUnit fires GET /api/memberships/Ana.
The controller calls the service's @MockitoBean, highlighted, which answers what was prepared with given(...).willReturn(...).
JUnit uses TestRestTemplate, highlighted, which sends the request over HTTP to the embedded server's port and reaches the controller.
The service calls the @TestConfiguration's fake bank, highlighted, which wins over the real gateway thanks to @Primary.
JUnit uses JacksonTester, highlighted, to write and read JSON in a context holding only what Jackson needs.
Final view: the real MockMvc, controller and service, and the gateway replaced by a mock inside the test context.
Step 1 of 9
The whole application to test one thing
EverythingTest wants to check a membership renewal. To do it, it starts the whole application with @SpringBootTest… including BankPaymentGateway, which tries to talk to the bank and fails.
Two problems:
- The test depends on an external system: it fails without a network, or worse, really charges.
- To check one controller rule it starts everything, including what it doesn't need.
Step 2 of 9
@SpringBootTest + MockMvc
@SpringBootTest is Spring Boot's "full" integration test:
- It searches upwards, from the test's package, for the class with
@SpringBootConfiguration(your@SpringBootApplication). - It starts the context with auto-configuration, as in production.
webEnvironment = MOCK(the default): a web context, but no real server.
With @AutoConfigureMockMvc you get a MockMvc to fire requests at the DispatcherServlet without a network: mvc.perform(post(...)).andExpect(status().isOk()).
Step 3 of 9
@MockitoBean: replacing a bean
To avoid calling the bank, @MockitoBean PaymentGateway payments:
- Creates a Mockito mock and registers it as a bean, replacing
BankPaymentGateway. - The real
MembershipServicereceives the mock. given(payments.charge(eq("Ana"), any())).willReturn(true)prepares the answer.- The mock is reset after each test.
Step 4 of 9
@WebMvcTest: only the web layer
Often you only want to test the controller: routes, parameters, JSON, status codes. @WebMvcTest(MembershipController.class) loads only the web layer:
- That controller, the
@ControllerAdvices, the converters (Jackson), the filters and aMockMvc. - It does not load
@Service,@Repositoryor regular@Componentclasses.
It's much faster than @SpringBootTest. There's a slice for each layer: @DataJpaTest, @JdbcTest, @JsonTest, @RestClientTest…
Step 5 of 9
In a slice, dependencies are mocks
MembershipController needs a MembershipService, but the web slice doesn't load it. If you do nothing, the context doesn't start: NoSuchBeanDefinitionException.
That's why the test declares @MockitoBean MembershipService memberships and tells it what to return in each case: a membership, an Optional.empty() for the 404 or an exception for the 402. With verify(memberships).renew("Leo") it checks the controller called the service.
Step 6 of 9
A real server: RANDOM_PORT
To test with real HTTP (container filters, full serialization, the port…):
@SpringBootTest(webEnvironment = RANDOM_PORT)starts the embedded Tomcat on a free port (DEFINED_PORTusesserver.port).@LocalServerPort int portgives you the chosen port.TestRestTemplate(with@AutoConfigureTestRestTemplatein Boot 4) already points athttp://localhost:{port}, so you use relative paths. In Boot 4 you also haveRestTestClient.
Step 7 of 9
@TestConfiguration: beans for tests only
In RealServerTest the bank isn't a mock but a hand-written fake: it approves charges under €100. It's declared in a @TestConfiguration class:
- It adds beans to the test context (here with
@Primary, to win overBankPaymentGateway). - The application's component scan does not pick it up, so it doesn't pollute other tests or the app.
- Nested and
static, it applies on its own; if it's top-level, bring it in with@Import.
Step 8 of 9
Other slices: @JsonTest and friends
Each layer has its slice, loading only its own pieces:
| Slice | Loads |
|---|---|
@WebMvcTest |
controllers, advice, converters, MockMvc |
@DataJpaTest |
entities, repositories, embedded DB, rollback |
@JdbcTest |
DataSource, JdbcTemplate, scripts, rollback |
@JsonTest |
Jackson as configured by Boot, JacksonTester |
@RestClientTest |
REST clients and MockRestServiceServer |
MembershipJsonTest uses @JsonTest and a JacksonTester to check the date comes out as "2026-12-28" and the JSON turns back into the same object.
Step 9 of 9
Recap
@SpringBootTest: full application;MOCK(default, withMockMvc) orRANDOM_PORT(real server,TestRestTemplate,@LocalServerPort).- Slices (
@WebMvcTest,@DataJpaTest,@JdbcTest,@JsonTest,@RestClientTest): one layer, faster. @MockitoBeanreplaces beans with mocks (formerly@MockBean);@MockitoSpyBeanspies on them.@TestConfiguration: test-only beans.- If a slice doesn't start, a mock for some dependency is missing.
Code
EverythingTest.java
/** Before: the whole application, the real bank gateway included, to check one controller rule. */
@SpringBootTest
class EverythingTest {
@Autowired
MembershipService memberships;
@Test
void theRealGatewayMakesTheTestUseless() {
assertThatThrownBy(() -> memberships.renew("Ana"))
.isInstanceOf(IllegalStateException.class); // "the bank is not reachable from here"
}
}MockMvcFullContextTest.java
@SpringBootTest // the whole application context (finds @SpringBootApplication)…
@AutoConfigureMockMvc // …plus MockMvc: no real server (webEnvironment = MOCK, the default)
class MockMvcFullContextTest {
@Autowired
MockMvc mvc;
@MockitoBean // replaces ONLY the bank gateway; the service and controller are real
PaymentGateway payments;
@Test
void renewsThroughTheRealServiceWithAMockedBank() throws Exception {
given(payments.charge(eq("Ana"), any())).willReturn(true);
mvc.perform(post("/api/memberships/Ana/renew"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.plan").value("monthly"));
}
}MockMvcFullContextTest.java
@SpringBootTest // the whole application context (finds @SpringBootApplication)…
@AutoConfigureMockMvc // …plus MockMvc: no real server (webEnvironment = MOCK, the default)
class MockMvcFullContextTest {
@Autowired
MockMvc mvc;
@MockitoBean // replaces ONLY the bank gateway; the service and controller are real
PaymentGateway payments;
@Test
void renewsThroughTheRealServiceWithAMockedBank() throws Exception {
given(payments.charge(eq("Ana"), any())).willReturn(true);
mvc.perform(post("/api/memberships/Ana/renew"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.plan").value("monthly"));
}
}MembershipControllerSliceTest.java
@WebMvcTest(MembershipController.class) // only the web layer: this controller, advice, Jackson, MockMvc
class MembershipControllerSliceTest {
@Autowired
MockMvc mvc;
@MockitoBean // a Mockito mock REGISTERED AS A BEAN in the test context
MembershipService memberships;
@Test
void returnsTheMembership() throws Exception {
given(memberships.find("Ana"))
.willReturn(Optional.of(new Membership("Ana", "monthly", LocalDate.of(2026, 12, 28))));
mvc.perform(get("/api/memberships/Ana"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.validUntil").value("2026-12-28"));
}
// …
}MembershipControllerSliceTest.java
@WebMvcTest(MembershipController.class) // only the web layer: this controller, advice, Jackson, MockMvc
class MembershipControllerSliceTest {
@Autowired
MockMvc mvc;
@MockitoBean // a Mockito mock REGISTERED AS A BEAN in the test context
MembershipService memberships;
@Test
void returnsTheMembership() throws Exception {
given(memberships.find("Ana"))
.willReturn(Optional.of(new Membership("Ana", "monthly", LocalDate.of(2026, 12, 28))));
mvc.perform(get("/api/memberships/Ana"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.validUntil").value("2026-12-28"));
}
// …
}RealServerTest.java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // a real Tomcat, free port
@AutoConfigureTestRestTemplate
@Import(RealServerTest.FakeBank.class)
class RealServerTest {
@LocalServerPort int port; // the port that was picked
@Autowired TestRestTemplate http; // already points at http://localhost:{port}
@TestConfiguration // extra beans for this test only, not picked up by scanning
static class FakeBank {
@Bean @Primary // wins over BankPaymentGateway
PaymentGateway alwaysApproves() {
return (athlete, amount) -> amount.compareTo(new BigDecimal("100")) < 0;
}
}
@Test
void aRealHttpRoundTrip() {
ResponseEntity<String> renewed = http.postForEntity("/api/memberships/Leo/renew", null, String.class);
ResponseEntity<String> missing = http.getForEntity("/api/memberships/Nobody", String.class);
assertThat(port).isPositive();
assertThat(renewed.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(missing.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
}RealServerTest.java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) // a real Tomcat, free port
@AutoConfigureTestRestTemplate
@Import(RealServerTest.FakeBank.class)
class RealServerTest {
@LocalServerPort int port; // the port that was picked
@Autowired TestRestTemplate http; // already points at http://localhost:{port}
@TestConfiguration // extra beans for this test only, not picked up by scanning
static class FakeBank {
@Bean @Primary // wins over BankPaymentGateway
PaymentGateway alwaysApproves() {
return (athlete, amount) -> amount.compareTo(new BigDecimal("100")) < 0;
}
}
@Test
void aRealHttpRoundTrip() {
ResponseEntity<String> renewed = http.postForEntity("/api/memberships/Leo/renew", null, String.class);
ResponseEntity<String> missing = http.getForEntity("/api/memberships/Nobody", String.class);
assertThat(port).isPositive();
assertThat(renewed.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(missing.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
}
}MembershipJsonTest.java
@JsonTest // only JSON: the ObjectMapper/JsonMapper as configured by Boot
class MembershipJsonTest {
@Autowired
JacksonTester<Membership> json;
@Test
void datesAreWrittenAsIsoStrings() throws Exception {
var membership = new Membership("Ana", "monthly", LocalDate.of(2026, 12, 28));
assertThat(json.write(membership)).extractingJsonPathStringValue("$.validUntil").isEqualTo("2026-12-28");
assertThat(json.parseObject("""
{"athlete": "Ana", "plan": "monthly", "validUntil": "2026-12-28"}""")).isEqualTo(membership);
}
}MockMvcFullContextTest.java
@SpringBootTest // the whole application context (finds @SpringBootApplication)…
@AutoConfigureMockMvc // …plus MockMvc: no real server (webEnvironment = MOCK, the default)
class MockMvcFullContextTest {
@Autowired
MockMvc mvc;
@MockitoBean // replaces ONLY the bank gateway; the service and controller are real
PaymentGateway payments;
@Test
void renewsThroughTheRealServiceWithAMockedBank() throws Exception {
given(payments.charge(eq("Ana"), any())).willReturn(true);
mvc.perform(post("/api/memberships/Ana/renew"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.plan").value("monthly"));
}
}