In-memory database for testing
By Mikael Ståldal
I have written about using an embedded database like HSQLDB or H2 for testing Java applications. This can still be useful (although JavaEE is not so popular any longer). But even though H2 claims to emulate PostgreSQL and several other popular production SQL databases, sometimes your application uses very specific features of a particular database and you need to test against the real thing to be really sure your application works correctly.
This can conveniently be done using Testcontainers, which run an instance of the real database in a Docker container for your tests. The downside is that this can be significantly slower than an embedded in-memory database like HSQLDB or H2.
However, you can speed it up by making sure that the database store its data in memory. Some databases, such as PostgreSQL, does not support this directly, but I learned a neat trick from a college of mine to do it anyway: use Docker’s tmpfs mount option.
You can do it like this for PostgreSQL:
docker run --tmpfs=/pgtmpfs -e PGDATA=/pgtmpfs postgres
or like this with Testcontainers:
new PostgreSQLContainer<>(PostgreSQLTestImages.POSTGRES_TEST_IMAGE).withTmpFs(Map.of("/pgtmpfs", "rw")).addEnv("PGDATA", "/pgtmpfs")