Tests con Spring Boot
- Idea clave
- Spring Boot añade sobre el TestContext dos herramientas: `@SpringBootTest` carga la aplicación completa (buscando tu `@SpringBootApplication`), y los *test slices* (`@WebMvcTest`, `@DataJpaTest`, `@JdbcTest`, `@JsonTest`, `@RestClientTest`…) cargan solo una capa. `@MockitoBean` sustituye un bean del contexto por un mock de Mockito.
- En el box
- Para probar una regla del controlador de membresías se arrancaba la aplicación entera, con la pasarela del banco real incluida. Elige el test adecuado, con @SpringBootTest o con los slices como @WebMvcTest, sustituye beans con @MockitoBean y prueba con MockMvc o con un servidor real.
JUnit llama a renew("Ana") en MembershipService, que llama a charge() en la pasarela real del banco, resaltada en rojo, y falla.
Dentro del contexto de test, JUnit lanza perform(post) con MockMvc; el contexto y MockMvc están resaltados.
La petición recorre MockMvc, el controlador y el servicio reales hasta el gateway, que ahora es un @MockitoBean, resaltado, que responde true.
Solo están MockMvc y MembershipController, resaltados, en el contexto de test; JUnit lanza GET /api/memberships/Ana.
El controlador llama al @MockitoBean del servicio, resaltado, que responde lo preparado con given(...).willReturn(...).
JUnit usa TestRestTemplate, resaltado, que envía la petición por HTTP al puerto del servidor embebido y llega al controlador.
El servicio llama al banco falso de la @TestConfiguration, resaltado, que gana a la pasarela real gracias a @Primary.
JUnit usa JacksonTester, resaltado, para escribir y leer JSON en un contexto que solo contiene lo necesario para Jackson.
Vista final: MockMvc, el controlador y el servicio reales y el gateway sustituido por un mock dentro del contexto de test.
Paso 1 de 9
Toda la aplicación para probar una cosa
EverythingTest quiere comprobar la renovación de una membresía. Para ello arranca la aplicación entera con @SpringBootTest… incluida BankPaymentGateway, que intenta hablar con el banco y falla.
Dos problemas:
- El test depende de un sistema externo: falla sin red, o peor, cobra de verdad.
- Para comprobar una regla del controlador arranca todo, también lo que no necesita.
Paso 2 de 9
@SpringBootTest + MockMvc
@SpringBootTest es el test de integración «completo» de Spring Boot:
- Busca hacia arriba, desde el paquete del test, la clase con
@SpringBootConfiguration(tu@SpringBootApplication). - Arranca el contexto con autoconfiguración, como en producción.
webEnvironment = MOCK(el valor por defecto): contexto web, pero sin servidor real.
Con @AutoConfigureMockMvc tienes un MockMvc para lanzar peticiones contra el DispatcherServlet sin red: mvc.perform(post(...)).andExpect(status().isOk()).
Paso 3 de 9
@MockitoBean: sustituir un bean
Para no llamar al banco, @MockitoBean PaymentGateway payments:
- Crea un mock de Mockito y lo registra como bean, sustituyendo a
BankPaymentGateway. MembershipService, real, recibe el mock.given(payments.charge(eq("Ana"), any())).willReturn(true)prepara la respuesta.- El mock se reinicia después de cada test.
Paso 4 de 9
@WebMvcTest: solo la capa web
Muchas veces solo quieres probar el controlador: rutas, parámetros, JSON, códigos de estado. @WebMvcTest(MembershipController.class) carga solo la capa web:
- Ese controlador, los
@ControllerAdvice, los conversores (Jackson), los filtros y unMockMvc. - No carga
@Service,@Repositoryni@Componentnormales.
Es mucho más rápido que @SpringBootTest. Hay un slice para cada capa: @DataJpaTest, @JdbcTest, @JsonTest, @RestClientTest…
Paso 5 de 9
En un slice, las dependencias son mocks
MembershipController necesita un MembershipService, pero el slice web no lo carga. Si no haces nada, el contexto no arranca: NoSuchBeanDefinitionException.
Por eso el test declara @MockitoBean MembershipService memberships y le dice qué devolver en cada caso: una membresía, un Optional.empty() para el 404 o una excepción para el 402. Con verify(memberships).renew("Leo") comprueba que el controlador llamó al servicio.
Paso 6 de 9
Un servidor de verdad: RANDOM_PORT
Para probar con HTTP real (filtros del contenedor, serialización completa, el puerto…):
@SpringBootTest(webEnvironment = RANDOM_PORT)arranca el Tomcat embebido en un puerto libre (DEFINED_PORTusaserver.port).@LocalServerPort int portte da el puerto elegido.TestRestTemplate(con@AutoConfigureTestRestTemplateen Boot 4) ya apunta ahttp://localhost:{port}, así que usas rutas relativas. En Boot 4 también tienesRestTestClient.
Paso 7 de 9
@TestConfiguration: beans solo para tests
En RealServerTest el banco no es un mock sino un fake escrito a mano: aprueba cobros de menos de 100 €. Se declara en una clase @TestConfiguration:
- Añade beans al contexto del test (aquí con
@Primary, para ganar aBankPaymentGateway). - El escaneo de componentes de la aplicación no la recoge, así que no contamina otros tests ni la app.
- Anidada y
static, se aplica sola; si es de nivel superior, la traes con@Import.
Paso 8 de 9
Otros slices: @JsonTest y compañía
Cada capa tiene su slice, que carga solo lo suyo:
| Slice | Carga |
|---|---|
@WebMvcTest |
controladores, advice, conversores, MockMvc |
@DataJpaTest |
entidades, repositorios, BD embebida, rollback |
@JdbcTest |
DataSource, JdbcTemplate, scripts, rollback |
@JsonTest |
Jackson configurado por Boot, JacksonTester |
@RestClientTest |
clientes REST y MockRestServiceServer |
MembershipJsonTest usa @JsonTest y un JacksonTester para comprobar que la fecha sale como "2026-12-28" y que el JSON vuelve a convertirse en el mismo objeto.
Paso 9 de 9
Resumen
@SpringBootTest: aplicación completa;MOCK(por defecto, conMockMvc) oRANDOM_PORT(servidor real,TestRestTemplate,@LocalServerPort).- Slices (
@WebMvcTest,@DataJpaTest,@JdbcTest,@JsonTest,@RestClientTest): una capa, más rápidos. @MockitoBeansustituye beans por mocks (antes@MockBean);@MockitoSpyBeanlos espía.@TestConfiguration: beans propios de los tests.- Si un slice no arranca, falta un mock de alguna dependencia.
Código
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"));
}
}