Scala Integration Testing with TestContainers Docker Library
Many of the times when we write Scala unit test cases, we need access to external services like databases, caches etc. Even though mocking works well for most of the cases, it’s the not the same thing. So it will be desirable to write test cases against the actual services. These test cases are known as integration test cases.
Challenge with Integration Test Cases
One of the biggest challenges with the integration test case is to set up the environment correctly. For example, if we need to write test cases again Mysql we need to set up the database and connection etc. Making it available for every developer’s environment including CI (continuous Integration) is tricky. This is one of the reasons where the integration test are run only in CI environments. But this discourages individual developers to write them and test them in their local environments.
Docker Based Environments
In recent years, using docker for setting up environment is becoming popular. Most of the databases, caches make their tools available as docker images. Most of the times CI tools will be setup using docker images. So if we need Mysql in CI, we will run the Mysql docker container.
This still doesn’t help in running these test cases in local machine. Expecting every developer to run the containers with right setup is not ideal. So most of these setup will be limited to CI systems.
Automating Docker Environment Setup
What if we can automate this docker based setup where the individual developer doesn’t need to worry about the same? This makes integration tests as easy as unit test cases as the developer doesn’t need to worry about setting up environments. Also now local and CI systems will behave exactly same.
That’s what testcontainers library helps to do.
Test Containers Library
TestContainers is a Java library which exposes running docker containers as test library. This exposes a simple library to run docker containers and interact with them as normal Java Library.
testcontainers-scala is a Scala port the same library which support ScalaTest integration.
In rest of the post, I will be discussing about how to use the library to run a test case running against mysql.
Look Great !! Would be interested to run the tests for my programs using your suggested approach.