Testcontainers: Real Databases in Integration Tests
Fast recall
Quick revision
Core answer
Whether you have practical Testcontainers experience and understand the lifecycle and performance implications
Starting a new container per test class — this multiplies startup time; a shared static container is almost always the right approach
Mention Testcontainers Cloud for CI environments where Docker is not available, and the ryuk container that handles automatic cleanup
Interview-ready guide
Interview answer
Testcontainers runs real infrastructure in Docker — PostgreSQL, Redis, Kafka — during tests. The biggest mistake is starting a new container per test class. A 3-second container startup multiplied by 20 test classes adds a minute of pure overhead.
The fix: shared containers. Define a static container in a base class, start it once for the entire suite, and reuse it. With withReuse(true) and testcontainers.reuse.enable=true, the container even survives between test runs during development.
Always pin image versions — postgres:15.4 not postgres:latest. Use @DynamicPropertySource for connection URLs because Testcontainers assigns random ports. And handle test isolation explicitly: @DataJpaTest rolls back transactions automatically, but Redis and Elasticsearch need manual cleanup between tests.
Pre-pull images in CI to avoid download time during test execution.
Testcontainers: Real Databases in Integration Tests
Direct Answer
Testcontainers is a Java library that programmatically manages Docker containers from within JUnit tests. It starts a real database (Postgres, MySQL, MongoDB, etc.) before tests run and stops it afterward. Best practices: use a static container shared across test classes to avoid repeated starts, use @DynamicPropertySource to inject the container's connection details, and add @AutoConfigureTestDatabase(replace = NONE) to prevent Spring from replacing your DataSource with H2.
Common Mistakes & Pitfalls
Starting a new container per test class — this multiplies startup time; a shared static container is almost always the right approach
Check your understanding
Answer these without looking back at the article.
- How do you handle schema migrations in Testcontainers tests with Flyway or Liquibase?
- What is the difference between @Container on a static vs instance field?
- How do you test a service that depends on both a database and Redis cache?
Related interview prep categories
1Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.