Yesterday I wrote about how to do unit and integration tests with Couchbase and TestContainers. One of the prerequisite for those tests was to have an image already built. Turns out you don’t have too. You can use TestContainers to build your own custom images just before running your tests and it is super easy. Thanks to Sergei Egorov for showing me the way!

Creating Images on the Fly

In the previous example an image would be instanciated with the following code:

The GenericContainer constructor would just take a String as parameter. That String being the name of the container you want to test. But the GenericContainer constructor also accepts a Future. Which happens to be what the ImageFromDockerfile class is. The Docker image will be created asynchronously with the parameters you will give.

Here I have copied all I needed into the resources folder of my project, which make them all accessible form the classpath. This is why I use the withFileFromClasspath method. You can also get a File from a String, an absolute path or a file. You’ll find more informations about this on TestContainers documentation.

And with that, your Docker image will be built automatically before running your tests. By default the images are deleted on exit but you can pass a flag to keep the images and avoid rebuilding them all the time. It really depends on your testing strategy.

Troubleshooting

While writing this I encountered a minor issue. All the resources that were used for the image creation lost their permissions, so I had to add a RUN chmod +x on all the resources I copy in the Dockerfile. This is now a known issue and the lovely and reactive people behind TestContainer are working on this. You can have a chat with them on their Slack channel, just like you can have a chat with Couchbase folks on our community channel.

Author

Posted by Laurent Doguin, Developer Advocate, Couchbase

Laurent is a Paris based Developer Advocate where he focuses on helping Java developers and the French community. He writes code in Java and blog posts in Markdown. Prior to joining Couchbase he was Nuxeo’s community liaison where he devoted his time and expertise to helping the entire Nuxeo Community become more active and efficient.

Leave a reply