Execute JUnit tests inside Docker container
In a dockerfile, checkout your code and do a "maven test" command, redirect the result in a file that is on a mounted directory.Each time you build the dockerfile, you do a unit test on your project.
With docker you also have a "docker test" command. I dont know if there is a plugin to use it on jenkins.
One way I found that works (using Gradle) is as follows. I know you are specifically referencing JUnit as your testing framework, but I actually think something similar to this could work.
Dockerfile (I called mine Dockerfile.UnitTests
):
FROM gradle:jdk8 AS test-stageWORKDIR /appCOPY . ./RUN gradle cleanRUN gradle testFROM scratch AS export-stageCOPY --from=test-stage /app/build/reports/tests/test/* /
I then run this with (in Gitbash on Windows 10):
> DOCKER_BUILDKIT=1 docker build -f Dockerfile.UnitTests --output type=tar,dest=UnitTests.tar .
This results in a tar file containing the test results displayed in an html file.
I executed the above in a Gitlab CI/CD pipeline and then sent the results to a web API for analysis.
A couple of assumptions:
- My project is set up for Gradle builds so I have the structure from the root of my project
src/test/java/groupname/projectname/testfile.java
- I am working in Windows 10 targeting Linux containers and using Gitbash.