Capítulo 4: Pruebas de Integración
Introducción
Las pruebas unitarias con mocks son rápidas pero no garantizan que los componentes funcionen juntos. Las pruebas de integración verifican que Spring, JPA y su base de datos colaboren correctamente.
🎯 Objetivos del Capítulo
Al final de este capítulo, usted sabrá:
- ✅ Utilizar @SpringBootTest
- ✅ Probar los repositories con @DataJpaTest
- ✅ Probar los controllers con @WebMvcTest
- ✅ Configurar los perfiles de prueba
- ✅ Utilizar TestContainers (bonus)
1. @SpringBootTest
Prueba de Integración Completa
@SpringBootTest // ← Carga el contexto completo de Spring
class ApplicationIntegrationTest {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
void contextLoads() {
// Verifica que la aplicación inicia
assertNotNull(userService);
}
@Test
void shouldCreateAndFindUser() {
User user = userService.create("John", "john@test.com");
User found = userService.findById(user.getId());
assertEquals("John", found.getName());
}
}
Opciones de @SpringBootTest
// Contexto completo con servidor web
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class FullStackTest {
@LocalServerPort
private int port;
}
// Sin servidor web (más rápido)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class ServiceTest { }
// Con configuración específica
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:testdb",
"logging.level.root=WARN"
})
class ConfiguredTest { }
2. @DataJpaTest
Prueba de Repository
@DataJpaTest // ← Configura solo JPA + H2
class UserRepositoryTest {
@Autowired
private UserRepository userRepository;
@Autowired
private TestEntityManager entityManager;
@Test
void shouldFindByEmail() {
// Arrange
User user = new User("John", "john@test.com");
entityManager.persistAndFlush(user);
// Act
Optional<User> found = userRepository.findByEmail("john@test.com");
// Assert
assertTrue(found.isPresent());
assertEquals("John", found.get().getName());
}
@Test
void shouldReturnEmptyWhenEmailNotFound() {
Optional<User> found = userRepository.findByEmail("unknown@test.com");
assertFalse(found.isPresent());
}
}
Lo que @DataJpaTest Configura
@DataJpaTest incluye:
├── H2 en memoria (por defecto)
├── Hibernate/JPA
├── TestEntityManager
├── Repositories
└── @Transactional (rollback después de cada prueba)
NO incluye:
├── @Service
├── @Controller
├── Spring Security
└── Otros componentes
Probar Consultas Personalizadas
@DataJpaTest
class ProductRepositoryTest {
@Autowired
private ProductRepository productRepository;
@Autowired
private TestEntityManager em;
@BeforeEach
void setUp() {
em.persist(new Product("Laptop", 1000.0, "Electronics"));
em.persist(new Product("Phone", 800.0, "Electronics"));
em.persist(new Product("Shirt", 50.0, "Clothing"));
em.flush();
}
@Test
void shouldFindByCategory() {
List<Product> electronics = productRepository.findByCategory("Electronics");
assertThat(electronics).hasSize(2);
}
@Test
void shouldFindByPriceRange() {
List<Product> products = productRepository.findByPriceBetween(100.0, 900.0);
assertThat(products)
.hasSize(1)
.extracting(Product::getName)
.containsExactly("Phone");
}
@Test
void shouldCountByCategory() {
long count = productRepository.countByCategory("Electronics");
assertEquals(2, count);
}
}
3. @WebMvcTest
Prueba de Controller (sin servicio real)
@WebMvcTest(UserController.class) // ← Prueba solo este controller
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean // ← Mock del servicio
private UserService userService;
@Test
void shouldReturnUser() throws Exception {
// Arrange
when(userService.findById(1L))
.thenReturn(new User(1L, "John", "john@test.com"));
// Act & Assert
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"))
.andExpect(jsonPath("$.email").value("john@test.com"));
}
@Test
void shouldReturn404WhenUserNotFound() throws Exception {
when(userService.findById(anyLong()))
.thenThrow(new UserNotFoundException(999L));
mockMvc.perform(get("/api/users/999"))
.andExpect(status().isNotFound());
}
}
@MockBean vs @Mock
// @MockBean: Para pruebas Spring (inyectado en el contexto)
@WebMvcTest
class ControllerTest {
@MockBean
private UserService userService; // Reemplaza el bean de Spring
}
// @Mock: Para pruebas unitarias puras (solo Mockito)
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
private UserRepository userRepository; // Mock simple de Mockito
}
4. Perfiles de Prueba
application-test.properties
# src/test/resources/application-test.properties
# Base de datos H2
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop
# Desactivar features
spring.flyway.enabled=false
spring.mail.host=localhost
Activar el Perfil
@SpringBootTest
@ActiveProfiles("test") // ← Utiliza application-test.properties
class MyIntegrationTest {
// ...
}
Anotación @TestPropertySource
@SpringBootTest
@TestPropertySource(properties = {
"spring.jpa.show-sql=false",
"app.feature.enabled=true"
})
class OverriddenPropertiesTest {
// ...
}
5. @Transactional en las Pruebas
Rollback Automático
@SpringBootTest
@Transactional // ← Rollback después de cada prueba
class TransactionalTest {
@Autowired
private UserRepository userRepository;
@Test
void test1() {
userRepository.save(new User("John"));
assertEquals(1, userRepository.count());
}
@Test
void test2() {
// La base de datos está vacía porque test1 fue revertido
assertEquals(0, userRepository.count());
}
}
@DataJpaTest es @Transactional por Defecto
@DataJpaTest // ← Ya es @Transactional
class RepositoryTest {
// Rollback automático después de cada prueba
}
6. Prueba con Datos Iniciales
@Sql
@SpringBootTest
@Sql("/test-data.sql") // ← Ejecuta antes de cada prueba
class SqlDataTest {
// ...
}
@Test
@Sql(scripts = "/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
void testWithCleanup() {
// ...
}
@SqlGroup
@SpringBootTest
@SqlGroup({
@Sql("/schema.sql"),
@Sql("/test-data.sql")
})
class MultiSqlTest {
// ...
}
Archivo test-data.sql
-- src/test/resources/test-data.sql
INSERT INTO users (id, name, email) VALUES (1, 'John', 'john@test.com');
INSERT INTO users (id, name, email) VALUES (2, 'Jane', 'jane@test.com');
INSERT INTO products (id, name, price) VALUES (1, 'Laptop', 1000.00);
7. TestContainers (Bonus)
¿Por qué?
H2 es práctico pero diferente de PostgreSQL/MySQL. TestContainers lanza bases de datos reales en Docker.
Configuración
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
Uso
@SpringBootTest
@Testcontainers
class PostgreSQLIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private UserRepository userRepository;
@Test
void shouldSaveToRealPostgres() {
User user = userRepository.save(new User("John", "john@test.com"));
assertNotNull(user.getId());
}
}
8. Slices de Prueba Spring Boot
Resumen
| Anotación | Contexto Cargado | Uso |
|---|---|---|
@SpringBootTest | Todo | Pruebas de integración completas |
@DataJpaTest | JPA + H2 | Pruebas de repository |
@WebMvcTest | MVC + Security | Pruebas de controller |
@JsonTest | Jackson | Pruebas de serialización |
@RestClientTest | RestTemplate | Pruebas de clientes REST |
Combinar con @MockBean
@DataJpaTest
@Import(UserService.class) // Importar el servicio
class UserServiceWithRealDbTest {
@Autowired
private UserService userService;
@MockBean
private EmailService emailService; // Mock externo
@Test
void shouldSaveUser() {
// userService utiliza el repository real
// emailService está mockeado
}
}
9. Resumen
Anotaciones Clave
| Anotación | Uso |
|---|---|
@SpringBootTest | Contexto completo |
@DataJpaTest | Pruebas JPA/Repository |
@WebMvcTest | Pruebas Controller |
@MockBean | Mock en el contexto Spring |
@ActiveProfiles | Perfil de prueba |
@Sql | Datos SQL |
@Transactional | Rollback automático |
Elección del Tipo de Prueba
┌─────────────────────────────────────────────┐
│ ¿Qué probar? │
├──────────────────────┬──────────────────────┤
│ Repository │ @DataJpaTest │
│ Solo controller │ @WebMvcTest │
│ Service con mocks │ @ExtendWith(Mockito) │
│ Stack completo │ @SpringBootTest │
│ Con base de datos real│ TestContainers │
└──────────────────────┴──────────────────────┘
🎯 Próximo Paso
Ya sabe cómo probar los repositories y servicios. Ahora, aprendamos a probar la API REST en detalle con MockMvc.
➡️ Capítulo 5: Pruebas REST API