Module 11 Lesson 4: Automated Testing with Docker
Verify your code in a clean environment. Learn how to use Docker to run unit and integration tests as part of your automated build process.
Module 11 Lesson 4: Automated Testing with Docker
Docker is the perfect environment for testing because it is Deterministic. If your tests pass in the container today, they will pass in the container tomorrow, regardless of what changes on your host machine.
1. Unit Testing in the Build
You can run your basic tests directly during the docker build process.
FROM python:3.9-slim
WORKDIR /app
COPY . .
RUN pip install requirements-dev.txt
# If tests fail here, the build STOPS and no image is created!
RUN pytest tests/unit
CMD ["python", "app.py"]
- Pros: Guaranteed that "Broken" code never becomes an image.
- Cons: Makes builds slower; includes "Test code" in the final image (Review Module 6 for how to fix this with multi-stage builds!).
2. Integration Testing with Docker Compose
Integration tests need a real database or a real API. Docker Compose handles this beautifully.
- Start the stack:
docker-compose up -d db redis - Run the test container:
docker-compose run --rm test-runner - Check the Exit Code: If the test runner returns
0, the tests passed. If it returns something else, the tests failed.
3. The "TestContainers" Library
Many languages (Java, Go, Python, Node) have a library called TestContainers.
- It allows your code to start a Docker container on the fly during execution.
- Your code says: "I need a Postgres database for 10 seconds."
- The library starts the container, your test runs against it, and then the library deletes the container for you.
4. Why Containerized Testing is Essential
- Isolation: Test A cannot leave "Dirty data" in the database that affects Test B.
- Parallelism: You can run 10 separate testing containers at once on the same machine without them fighting over ports.
- Mocking Infrastructure: You can use a container to "Mimic" a complex service (like AWS S3 using
LocalStack) without paying for the real service.
Exercise: The Failing Build
- Create a simple Python image.
- Add a
tests/folder with a filetest_logic.pythat has one test:assert 1 == 2(This will fail!). - Add
RUN pytest tests/to your Dockerfile. - Try to build the image:
docker build -t fail-test .. - Did the image build? What was the error message?
- Now, fix the test and build again. Success!
- Why is this "Fail-Fast" behavior good for a team of 100 people?
Summary
Testing in Docker is about Certainty. By wrapping your tests in a container, you remove the "But it works on my machine" variable and ensure that your software is healthy before it ever reaches the registry.
Next Lesson: Housekeeping: Image cleanup and lifecycle in registries.