Play with Testcontainers


What is “Testcontainers”?

Testcontainers is a Java 8 library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container. see So you don’t need any longer to create and customize Docker Compose to configure databases or anything else that you need for testing.

Let’s look at an example with Spring Boot, Docker and Testcontainers. Alle sources are available here:

Before you start you must be sure that a Docker or Docker machine is installed on the machine you are running your tests on.

Let’s initialize a Spring Boot service from

After that we’ll add the Testcontainers dependency to the generated project from the Spring initializer:

Testcontainers Adapters 

So, let’s say we need for our tests the following databases: PostgreSQL and MySQL, and also Selenium. The benefit for Testcontainers is that you don’t need to configure those  dependencies in the Docker Compose file. You just have to add the adapter you need. Testcontainers offers the following adapters:

  • vault
  • testcontainers
  • spock
  • selenium
  • pulsar
  • postgresql
  • oracle-xe
  • nginx
  • neo4j
  • mysql
  • mssqlserver
  • mockserver
  • mariadb
  • localstack
  • kafka
  • jdbc
  • influxdb
  • elasticsearch
  • dynalite
  • database-commons

For more information see:

PostgreSQL with Testcontainers 

So, I add PostgreSQL, MySQL and Selenium to the dependencies of the project:

Let’s write a test case using PostgreSQL: I use HikariCP as the JDBC driver because it is much faster than other drivers, see here

You see now, we just use the PostgreSQLContainer to configure the database we need for the test

and the performQuery method:

We can also use the @Rule in the JUnit test:

and then you get the connection from the PostgresSQLContainer:

MySQL with Testcontainers 

For MySQL it is the same procedure as with PostgreSQLContainer. You can use the MySQLContainer from org.testcontainers.mysql:

Here follows the test example to check the MySQL version:

Selenium with Testcontainers 

For the Selenium test, Testcontainers offers the BrowserWebDriverContainer. For the Selenium test you need the Selenium remote driver for the automated browsers.

and then you can the test your frontEnd project like:


Integration tests, i.e. tests that interact with external systems, are also required to fully cover all aspects of testing. If these systems are databases, Testcontainers can be used for them. The tests then run against a correct instance of the selected database, thus increasing confidence that the code tested in this way is actually working.
Apart from databases, Testcontainers can also be used for tests that require a running browser. Above all, the effort to install the appropriate browser locally is eliminated and thus offers a clear advantage.