5.3.1.3 Builder Test Execution
A focused guide to Builder Test Execution, connecting core concepts with practical Docker and container operations.
Builder test execution is the practice of running an application's automated test suite as part of a dedicated build stage, ensuring tests run under conditions closely matching the final build environment while keeping the testing tools and test code itself entirely out of the final runtime image.
Running Tests Within a Dedicated Stage
A test stage, built on top of whatever dependency setup the application needs, runs the test suite as its primary purpose, with the build failing outright if tests fail.
FROM node:20 AS dependencies
WORKDIR /app
COPY package*.json ./
RUN npm install
FROM dependencies AS test
COPY . .
RUN npm test
FROM dependencies AS build
COPY . .
RUN npm run build
If npm test exits with a non-zero status, the entire build fails at this stage, preventing a build with failing tests from proceeding any further.
Building Only the Test Stage in CI
A CI pipeline can specifically target the test stage, running tests as a distinct, separately reportable step in the pipeline without needing to also build the final production image.
docker build --target test -t myapp:test .
Why Testing Inside a Container Provides Value
Running tests within the same kind of containerized environment the application will actually run in catches environment-specific issues that running tests directly on a developer's local machine might miss entirely.
docker build --target test --no-cache -t myapp:test .
Running without cache occasionally ensures the test stage isn't silently passing due to a stale, cached result that no longer reflects the current source code.
Why Builder Test Execution Matters
Incorporating test execution directly into the build process, as its own dedicated stage, creates a strong, automatically enforced gate ensuring that an image is never produced from source code that fails its own test suite, while still keeping all the testing infrastructure cleanly separated from the final runtime image.