Dependências reais com Testcontainers
Teste usando bancos de dados reais em contêineres.
Dependências reais com Testcontainers é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Testcontainers
Testcontainers runs real services — PostgreSQL, Redis, Kafka — inside Docker containers during tests.
You test against the real database, not an in-memory substitute, catching dialect and behavior differences.
Adding the Dependency
Add the Testcontainers JUnit and database modules to your build.
// build.gradle
testImplementation "org.testcontainers:junit-jupiter"
testImplementation "org.testcontainers:postgresql"The @Testcontainers Annotation
@Testcontainers on the test class activates container lifecycle management.
@Testcontainers
@SpringBootTest
class UserRepositoryIT {
// containers declared here
}Declaring a PostgreSQLContainer
A static @Container field defines the database image to start.
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");Wiring the Datasource
Use @DynamicPropertySource to inject the container's generated JDBC URL into Spring.
@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url",
postgres::getJdbcUrl);
registry.add("spring.datasource.username",
postgres::getUsername);
registry.add("spring.datasource.password",
postgres::getPassword);
}A Full Repository Test
Now repository tests run against real PostgreSQL.
@Test
void savesAndReads() {
User saved = repository.save(new User("Alice"));
assertThat(repository.findById(saved.getId()))
.isPresent();
}Static vs Instance Containers
A static container starts once for all tests in the class (faster). A non-static container restarts for each test (more isolation).
Other Container Types
Testcontainers has modules for many services.
@Container
static GenericContainer<?> redis =
new GenericContainer<>("redis:7")
.withExposedPorts(6379);Reusing Containers
Enable container reuse to speed up local runs across test executions.
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16")
.withReuse(true);Spring Boot Service Connections
Spring Boot 3.1+ can auto-configure the datasource from a container with @ServiceConnection, removing the need for @DynamicPropertySource.
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16");Docker Requirement
Testcontainers needs a running Docker engine on the machine or CI agent. Without Docker the tests fail to start containers.
Quick Check
Test your understanding of Testcontainers.
Recap
You learned to test against real dependencies:
@Testcontainers+@Containerstart Docker servicesPostgreSQLContainerfor a real database@DynamicPropertySourceor@ServiceConnectionwires the datasource- Requires a running Docker engine
Perguntas Frequentes
A aula “Dependências reais com Testcontainers” é grátis?
Sim — o texto completo de “Dependências reais com Testcontainers” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
O que vou aprender em “Dependências reais com Testcontainers”?
Teste usando bancos de dados reais em contêineres. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?
Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Dependências reais com Testcontainers”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?
Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Testes unitários com JUnit e Mockito
- Testes da camada web com MockMvc
- Testes de integração com @SpringBootTest
- Dependências reais com Testcontainers