In my previous post on testing, I described how to use TestContainers to provide realistic test environments for database tests. This comment revealed the downside:

…as noted above, there always seems to be some drawback. In this case, the overhead of starting the Docker image and everything it contains will increase your overall build time.

As a reminder, here’s the TestContainer-specific code. Note the instance member postgres, and the JUnit Rule that re-initializes it on a per-method basis.

Given that the huge increase in test duration results from Docker container start-up times, we can instead use a JUnit ClassRule to start up one container and re-use it for every test in the class. This means you should no longer run these tests in parallel, but the performance gains massively outweigh test parallelization.

The amount of time saved depends on the number of test methods in a class. I have some test classes that have upwards of 30 tests each, and in these cases the execution time drops from minutes to seconds. Not bad for changing a couple of lines of code.

Leave a Reply

Your email address will not be published. Required fields are marked *