Cheatsheet
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.
Diagram (UML)
flowchart TB
q{"What do you want to test?"}
q -- "one class, its logic" --> unit["Unit test<br/>JUnit + Mockito, no Spring"]
q -- "a controller: routes, JSON, status" --> web["@WebMvcTest(Controller.class)<br/>+ @MockitoBean for its services"]
q -- "repositories / queries" --> data["@DataJpaTest · @JdbcTest<br/>embedded DB, rollback"]
q -- "JSON mapping" --> json["@JsonTest<br/>JacksonTester"]
q -- "a REST client" --> client["@RestClientTest<br/>MockRestServiceServer"]
q -- "everything wired together" --> full["@SpringBootTest"]
full -- "webEnvironment = MOCK (default)" --> mock["@AutoConfigureMockMvc<br/>MockMvc, no server"]
full -- "RANDOM_PORT / DEFINED_PORT" --> real["real Tomcat<br/>TestRestTemplate + @LocalServerPort"]
full -. "replace an external bean" .-> mb["@MockitoBean / @TestConfiguration"]Key pieces
@SpringBootTest(webEnvironment = MOCK | RANDOM_PORT | DEFINED_PORT | NONE)@AutoConfigureMockMvc+MockMvc;TestRestTemplate/RestTestClient+@LocalServerPortfor a real server- Slices:
@WebMvcTest(Controller.class),@DataJpaTest,@JdbcTest,@JsonTest,@RestClientTest @MockitoBeanand@MockitoSpyBean(Spring Framework 6.2+); formerly@MockBean/@SpyBean@TestConfiguration: extra beans for tests, not picked up by scanningspring-boot-starter-test: JUnit 5, AssertJ, Hamcrest, Mockito, JSONassert, JsonPath, Spring Test
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"));
}
}Remember for the exam
@SpringBootTestsearches upwards for the@SpringBootConfigurationclass and starts the full context with auto-configuration- The default
webEnvironmentisMOCK: a web context but no server; you test withMockMvc RANDOM_PORTstarts a real server on a free port; you read it with@LocalServerPort@WebMvcTestloads controllers,@ControllerAdvice, converters, filters andMockMvc, but not@Serviceor@Repository@MockitoBeanadds or replaces a bean with a mock; it's reset after each test- Slices and
@SpringBootTestare cached too; each different@MockitoBeanchanges the cache key
Exam traps
- In a
@WebMvcTest, if the controller needs a service and you don't mock it, the context doesn't start (NoSuchBeanDefinitionException) @MockBeanis deprecated since Boot 3.4 and removed in Boot 4: the equivalent is@MockitoBean(packageorg.springframework.test.context.bean.override.mockito)- With
MockMvcthere's no server or network: testing ports, TLS or container filters needsRANDOM_PORT - A
@SpringBootTestwithRANDOM_PORTand@Transactionaldoes not roll back what the server does (it runs on another thread) - A nested
@TestConfigurationis detected on its own; a top-level one must be imported with@Import