More often than not, developers want to test the source code against a real database instead of Fakes or Test Doubles during a CI job in order to verify the code works as expected. Therefore a clean database is needed for every CI-job. One solution is to use a shared instance of the database in your existing test-environment which get cleaned before and after a job. But this suffers from being “shared” and you never can run multiple CI-jobs in parallel without jobs interfering with each other.
A much better solution is to use the Sidecar-Pattern with Docker.
A sidecar is a specific docker container starting with the main CI-job
and provides specific functionality like a fresh database during the
test run. In a Jenkinsfile
this is accomplished with:
docker.image(<imagename>.withRun(<docker run parameters>) {<run your tests>}
For more info about Docker, sidecars and Jenkins, see Use Docker in Jenkins Pipelines
A full example of a Jenkinsfile with a Postgres-DB sidecar container:
|
|
This pattern is so successful that many libraries exist using this pattern in order to provide Databases, Message Brokers and even Web Browser as sidecars, e.g the Java library TestContainers.