Rafael Souza

Talking about Software Engineering

Docker for Database Mock

In the Java world the most popular approach to test with mocked/in memory databases is using H2 or HSQLDB. These databases work well and can emulate some database syntax and behavior, but like most emulations, this is superficial, imperfect and doesn’t cover important database features.

So, sometime ago I decided to create a Java library to easily launch a docker container with a real database instance (like postgres, mysql and so on). This database will be running as an in memory test database and the process to do that is lightweight and quick, what is really useful for test purposes.


Alt text


Pull the database images

sudo docker pull postgres

Enable Docker remote REST API:

$ echo "DOCKER_OPTS='-H tcp:// -H unix:///var/run/docker.sock'" > /etc/default/docker
$ service docker restart

Read here more about it!

Maven dependencies:


How to use

Basically you need to add two annotations in your tests:

@DockerDatabaseConfig(type = DatabaseType.POSTGRES, port = 5432)
public class BlogRepositoryTest {
  • @RunWith(DockerDatabaseRunner.class): The test runner that will enable test listeners (start database before start tests and stop afterwards)
  • @DockerDatabaseConfig(type = DatabaseType.POSTGRES, port = 5432): The database configuration. type is the database that you want to launch (only Postgres 9.4 is supported at this monent). port the port that the database you listen for connections.

You can also see the example projects here: examples