When automated tests depend on a database or external service, Testcontainers supplies a practical virtual test environment instead of relying on a separately maintained installation. It uses Docker to start containerized dependencies when tests run. section 8.7 section 8.7.1
Use Testcontainers to:
- Start PostgreSQL, MongoDB, Elasticsearch, Kafka, RabbitMQ, or another Docker-packaged service. section 8.7 section 8.7.1
- Add the core library and service-specific dependencies to a Maven POM or Gradle build script. section 8.7.1
- Choose a service-specific container class, such as PostgreSQLContainer or KafkaContainer, or use GenericContainer for an arbitrary image. section 8.7.1
- Customize less common dependencies through Docker Compose or a custom Docker configuration file. section 8.7.1
- Integrate containers with JUnit, Spock, Cucumber, or Spring Boot-based tests. section 8.7.1 section 8.8
Starting a PostgreSQL dependency
Declare a PostgreSQLContainer with a Docker image, database name, username, and password; call start(); then obtain the generated JDBC URL and connect the application under test to that container.
Sharing or isolating containers
Encapsulate a database container in a helper class when several tests can reuse it. A static instance can reduce startup work; a ThreadLocal instance provides separate containers for concurrent test threads.
Connecting Spring Boot and Cucumber
Register the container's JDBC URL, username, and password through DynamicPropertySource, then let Spring inject the repository used by Cucumber step definitions.




