Pular para o conteúdo principal

Capítulo 4: Testes de Integração

Introdução​

Os testes unitários com mocks são rápidos, mas não garantem que os componentes funcionem juntos. Os testes de integração verificam se Spring, JPA e seu banco de dados colaboram corretamente.


🎯 Objetivos do Capítulo​

Ao final deste capítulo, você saberá:

  1. ✅ Utilizar @SpringBootTest
  2. ✅ Testar os repositórios com @DataJpaTest
  3. ✅ Testar os controllers com @WebMvcTest
  4. ✅ Configurar perfis de teste
  5. ✅ Utilizar TestContainers (bônus)

1. @SpringBootTest​

Teste de Integração Completo​

@SpringBootTest  // ← Carrega o contexto Spring completo
class ApplicationIntegrationTest {

@Autowired
private UserService userService;

@Autowired
private UserRepository userRepository;

@Test
void contextLoads() {
// Verifica se a aplicação inicia
assertNotNull(userService);
}

@Test
void shouldCreateAndFindUser() {
User user = userService.create("John", "john@test.com");

User found = userService.findById(user.getId());

assertEquals("John", found.getName());
}
}

Opções do @SpringBootTest​

// Contexto completo com servidor web
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class FullStackTest {
@LocalServerPort
private int port;
}

// Sem servidor web (mais rápido)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class ServiceTest { }

// Com configuração específica
@SpringBootTest(properties = {
"spring.datasource.url=jdbc:h2:mem:testdb",
"logging.level.root=WARN"
})
class ConfiguredTest { }

2. @DataJpaTest​

Teste de Repository​

@DataJpaTest  // ← Configura apenas 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());
}
}

O que @DataJpaTest Configura​

@DataJpaTest inclui:
├── H2 em memória (padrão)
├── Hibernate/JPA
├── TestEntityManager
├── Repositories
└── @Transactional (rollback após cada teste)

NÃO inclui:
├── @Service
├── @Controller
├── Spring Security
└── Outros componentes

Testar 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​

Teste de Controller (sem serviço real)​

@WebMvcTest(UserController.class)  // ← Testa apenas este controller
class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean // ← Mock do serviço
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 testes Spring (injetado no contexto)
@WebMvcTest
class ControllerTest {
@MockBean
private UserService userService; // Substitui o bean Spring
}

// @Mock: Para testes unitários puros (apenas Mockito)
@ExtendWith(MockitoExtension.class)
class ServiceTest {
@Mock
private UserRepository userRepository; // Mock simples do Mockito
}

4. Perfis de Teste​

application-test.properties​

# src/test/resources/application-test.properties

# Banco de dados 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

# Desabilitar features
spring.flyway.enabled=false
spring.mail.host=localhost

Ativar o Perfil​

@SpringBootTest
@ActiveProfiles("test") // ← Usa application-test.properties
class MyIntegrationTest {
// ...
}

Anotação @TestPropertySource​

@SpringBootTest
@TestPropertySource(properties = {
"spring.jpa.show-sql=false",
"app.feature.enabled=true"
})
class OverriddenPropertiesTest {
// ...
}

5. @Transactional nos Testes​

Rollback Automático​

@SpringBootTest
@Transactional // ← Rollback após cada teste
class TransactionalTest {

@Autowired
private UserRepository userRepository;

@Test
void test1() {
userRepository.save(new User("John"));
assertEquals(1, userRepository.count());
}

@Test
void test2() {
// O banco está vazio porque test1 foi rollback
assertEquals(0, userRepository.count());
}
}

@DataJpaTest é @Transactional por Padrão​

@DataJpaTest  // ← Já é @Transactional
class RepositoryTest {
// Rollback automático após cada teste
}

6. Teste com Dados Iniciais​

@Sql​

@SpringBootTest
@Sql("/test-data.sql") // ← Executa antes de cada teste
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 {
// ...
}

Arquivo 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 (Bônus)​

Por quê?​

H2 é prático, mas diferente do PostgreSQL/MySQL. TestContainers executa bancos de dados reais no Docker.

Configuração​

<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>

Utilização​

@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 Teste Spring Boot​

Resumo​

AnotaçãoContexto CarregadoUtilização
@SpringBootTestTudoTestes de integração total
@DataJpaTestJPA + H2Testes de repository
@WebMvcTestMVC + SecurityTestes de controller
@JsonTestJacksonTestes de serialização
@RestClientTestRestTemplateTestes de clientes REST

Combinar com @MockBean​

@DataJpaTest
@Import(UserService.class) // Importa o serviço
class UserServiceWithRealDbTest {

@Autowired
private UserService userService;

@MockBean
private EmailService emailService; // Mock externo

@Test
void shouldSaveUser() {
// userService usa o repository real
// emailService é mockado
}
}

9. Resumo​

Anotações-Chave​

AnotaçãoUso
@SpringBootTestContexto completo
@DataJpaTestTestes JPA/Repository
@WebMvcTestTestes Controller
@MockBeanMock no contexto Spring
@ActiveProfilesPerfil de teste
@SqlDados SQL
@TransactionalRollback automático

Escolha do Tipo de Teste​

┌─────────────────────────────────────────────┐
│ O que testar? │
├──────────────────────┬──────────────────────┤
│ Repository │ @DataJpaTest │
│ Apenas Controller │ @WebMvcTest │
│ Service com mocks │ @ExtendWith(Mockito) │
│ Stack completo │ @SpringBootTest │
│ Com banco real │ TestContainers │
└──────────────────────┴──────────────────────┘

🎯 Próxima Etapa​

Você já sabe testar repositórios e serviços. Agora, vamos aprender a testar a API REST em detalhes com MockMvc.

➡️ Capítulo 5: Testes REST API


⬅️ Voltar ao Módulo 9