Spring Boot 4 Microservices & REST APIs · Lección

Dependencias reales con Testcontainers

Pruebe con bases de datos reales en contenedores

Lección 4 de 413 pasos

Dependencias reales con Testcontainers es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 4 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.

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 + @Container start Docker services
  • PostgreSQLContainer for a real database
  • @DynamicPropertySource or @ServiceConnection wires the datasource
  • Requires a running Docker engine
Gratis para empezar

Aprende Java con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
24
Lecciones
93

Preguntas frecuentes

¿La lección «Dependencias reales con Testcontainers» es gratis?

Sí — el texto completo de «Dependencias reales con Testcontainers» 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 «Dependencias reales con Testcontainers»?

Pruebe con bases de datos reales en contenedores 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 4 de 4.

¿Cuánto tiempo toma la lección «Dependencias reales con Testcontainers»?

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

  1. Pruebas unitarias con JUnit y Mockito
  2. Pruebas de la capa web con MockMvc
  3. Pruebas de integración con @SpringBootTest
  4. Dependencias reales con Testcontainers
← Volver a Spring Boot 4 Microservices & REST APIs