Pruebas de integración con @SpringBootTest
Pruebe todo el contexto de la aplicación
Pruebas de integración con @SpringBootTest es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What is an Integration Test
An integration test exercises multiple layers together — controller, service, repository — using a real Spring context.
It catches wiring and configuration problems that unit tests miss.
@SpringBootTest
@SpringBootTest boots the entire application context, loading all beans.
@SpringBootTest
class ApplicationIntegrationTest {
@Autowired
UserService userService;
@Test
void contextLoads() {
assertThat(userService).isNotNull();
}
}WebEnvironment Modes
Control whether a real server starts with the webEnvironment attribute.
MOCK(default) — mock servlet environmentRANDOM_PORT— real server on a random port
@SpringBootTest(
webEnvironment = WebEnvironment.RANDOM_PORT)
class ApiTest { }Testing with TestRestTemplate
With a real port you can make actual HTTP calls using TestRestTemplate.
@Autowired
TestRestTemplate restTemplate;
@Test
void getsUser() {
ResponseEntity<User> response =
restTemplate.getForEntity("/users/1", User.class);
assertThat(response.getStatusCode())
.isEqualTo(HttpStatus.OK);
}WebTestClient
WebTestClient is a fluent client that works for both MVC and WebFlux apps.
@Autowired
WebTestClient webTestClient;
@Test
void getsUser() {
webTestClient.get().uri("/users/1")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.name").isEqualTo("Alice");
}Using a Test Database
By default Spring Boot can replace your datasource with an in-memory H2 database for tests.
@SpringBootTest
@AutoConfigureTestDatabase
class RepositoryIntegrationTest {
@Autowired UserRepository repository;
}Test Properties
Override configuration for tests with @TestPropertySource or an application-test.properties profile.
@SpringBootTest
@TestPropertySource(properties = {
"feature.enabled=false"
})
class FeatureTest { }Activating Profiles
Use @ActiveProfiles to run with a specific Spring profile.
@SpringBootTest
@ActiveProfiles("test")
class ServiceTest { }Transactional Rollback
Annotate tests with @Transactional so each test's database changes roll back automatically, keeping tests isolated.
@SpringBootTest
@Transactional
class UserPersistenceTest {
@Test
void savesAndRollsBack() {
repository.save(new User("Alice"));
}
}Slicing for Speed
Full @SpringBootTest is slow. Prefer slices like @DataJpaTest or @WebMvcTest when you only need one layer.
@DataJpaTest
@DataJpaTest loads only JPA components and an embedded database — ideal for repository tests.
@DataJpaTest
class UserRepositoryTest {
@Autowired UserRepository repository;
@Test
void findsByName() {
repository.save(new User("Alice"));
assertThat(repository.findByName("Alice"))
.hasSize(1);
}
}Quick Check
Test your understanding of integration testing.
Recap
You learned to write integration tests:
@SpringBootTestloads the full contextRANDOM_PORT+TestRestTemplate/WebTestClientfor real HTTP@Transactionalrolls back DB changes- Use slices for speed
Preguntas frecuentes
¿La lección «Pruebas de integración con @SpringBootTest» es gratis?
Sí — el texto completo de «Pruebas de integración con @SpringBootTest» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «Pruebas de integración con @SpringBootTest»?
Pruebe todo el contexto de la aplicación Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Pruebas de integración con @SpringBootTest»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Pruebas unitarias con JUnit y Mockito
- Pruebas de la capa web con MockMvc
- Pruebas de integración con @SpringBootTest
- Dependencias reales con Testcontainers