Skip to Content
Course content

97: Integration Testing with Testcontainers

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're a professional chef testing a new recipe for a complex cake. You could try to simulate the oven's heat with a hair dryer and a desk lamp, but that's not going to tell you if the cake actually rises. To know for sure, you need a real oven. But you don't want to permanently install a massive industrial oven in your living room just for one test; you just want one that appears when you're baking and vanishes the moment the cake is out of the oven.

That's exactly what Testcontainers does for your Scala applications. In the past, we usually handled integration tests in one of two bad ways: we either used an "in-memory" version of a database (like H2) which behaves differently than the real thing, or we pointed our tests at a shared "dev" database that someone else inevitably broke at 3 AM. Testcontainers lets you spin up a real Docker container—Postgres, Kafka, Redis, you name it—specifically for the duration of your test suite, and then wipes it clean when you're done.

The "Shared Dev DB" Nightmare

I've spent way too many hours debugging tests that failed not because the code was wrong, but because another developer had inserted a row into the shared test database that violated a unique constraint in my test. It's a nightmare. By using Testcontainers, every developer (and the CI server) gets their own isolated, identical instance of the infrastructure. If the test passes on your machine, it'll pass in the pipeline because the environment is literally the same Docker image.

Wiring Postgres into your Scala Suite

Let's look at how this actually works. I'm assuming you've got Docker installed on your machine. To get started, you'll need the testcontainers-scala-postgresql module. Instead of hardcoding a JDBC URL in your application.conf, we're going to let the container tell us where it's running.

import org.testcontainers.scala.postgresql.PostgreSQLContainer
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.BeforeAndAfterAll

class UserRepositorySpec extends AnyWordSpec with BeforeAndAfterAll {

  // We define the container here. It's not running yet.
  val postgres = PostgreSQLContainer("postgres:15-alpine")

  override def beforeAll(): Unit = {
    // This actually starts the Docker container
    postgres.start()
  }

  override def afterAll(): Unit = {
    // This kills the container and cleans up the disk space
    postgres.stop()
  }

  "UserRepository" should {
    "save and retrieve a user" in {
      // The magic is here: the container assigns a random available port
      val jdbcUrl = postgres.getJdbcUrl
      val username = postgres.getUsername
      val password = postgres.getPassword

      val repo = new UserRepository(jdbcUrl, username, password)
      val user = User("123", "Alice")
      
      repo.save(user)
      repo.findById("123") shouldBe Some(user)
    }
  }
}

Dealing with the Startup Tax

Now, I'll be honest with you: starting a Docker container for every single test class is slow. If you have 50 spec files, your build time will explode. I usually recommend using a "Singleton" pattern for your containers. You create a trait or an object that holds the container instance and start it once for the entire test run, rather than per-class. It's a bit more setup, but it saves you from staring at a loading bar for ten minutes every time you run sbt test.

When to skip the container

You might be wondering if you should replace all your unit tests with this. Absolutely not. Integration tests are expensive. Keep your business logic in "pure" Scala functions that you can test in milliseconds. Use Testcontainers for the "edges" of your system—the parts where your code actually touches the network or the disk. If you're testing a complex sorting algorithm, don't spin up a database just to hold the list you're sorting.




📋 Practical Task

Implementing a Redis Cache Integration Test

You are building a session management service that uses Redis to store user tokens. You've written the SessionStore class, but you're currently using a mock for the Redis client, and you suspect the serialization logic is actually broken.

Your task: Create a ScalaTest specification that uses Testcontainers to spin up a real Redis instance.

  • Add the testcontainers-scala-redis dependency to your conceptual build.
  • Define a GenericContainer (or the specific Redis container) using the redis:7-alpine image.
  • In the test, retrieve the mapped port from the container (since Redis doesn't run on 6379 inside the container mapping, it uses a random ephemeral port on your host).
  • Initialize your SessionStore with this dynamic port.
  • Write a test case that saves a session token and retrieves it to verify that the real Redis instance is communicating correctly with your Scala code.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.