Testcontainers
- Kotlin course
- Advanced
- Lesson 46/83
- 5 min
Learn integration testing with Testcontainers.
Real databases with Testcontainers
Testcontainers starts real Docker containers during tests. It lets you use real PostgreSQL, Redis or Kafka; you test against the real version instead of in-memory H2.
Example: val container = PostgreSQLContainer("postgres:16"); container.start(). container.jdbcUrl gives the real connection URL. When the test ends, container.stop() shuts it down. This narrows the gap between test and production.
withContainer and auto-cleanup
Testcontainers integrates with JUnit 5 via @Testcontainers and @Container annotations for automatic management. The container starts before tests and stops afterward.
Example: @Container val postgres = PostgreSQLContainer("postgres:16"). You get real connection details via jdbcUrl, username and password. This pattern manages the container lifecycle with no code duplication.
Practice Define a GenericContainer subclass
Define a simple class RedisContainer that extends GenericContainer<Nothing>("redis:7") and adds a val port = firstMappedPort property. In main create a RedisContainer() instance and print "started" instead of it.port.
Starter code
import org.testcontainers.containers.GenericContainer
// RedisContainer: extends GenericContainer, redis:7 image
// in main create an instance and print "started"Sample solution
import org.testcontainers.containers.GenericContainer
open class RedisContainer :
GenericContainer<Nothing>("redis:7") {
val port: Int
get() = firstMappedPort
}
fun main() {
RedisContainer().use {
println("started")
}
}Expected output
started
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the PostgreSQLContainer definition
val container = ____("postgres:16")
container.start()
val container = PostgreSQLContainer("postgres:16")
container.start()
Explanation: PostgreSQLContainer starts a real PostgreSQL.
2 What is the main advantage of Testcontainers?
- Testing in the same environment as production Correct answer
- Not requiring Docker
- Low memory usage
- Slower tests
Explanation: Testcontainers tests with real versions, improving production parity.
3 Match the Testcontainers parts
| Term | Meaning |
|---|---|
PostgreSQLContainer |
Postgres image |
container.start() |
Start |
container.jdbcUrl |
Connection URL |
container.stop() |
Stop |