Some things in software development require more than mocks and unit testing. If your application uses a database it makes sense to also hit that database in automated testing to ensure custom SQL queries work correctly, Hibernate relations are set up properly and also that database migrations are successful.
This blog post was written with a focus on the latter. I will be using Spring Boot talking to a PostgreSQL database. The database structure is managed via Flyway and, basically customary for Java applications, Maven serves as the build and dependency management tool. Docker will also play a role because we’ll be creating and running a PostgreSQL docker image for testing. From Maven. Every time the test is executed. And to spice things up, we’ll also create a custom database and user in that dockerized PSQL image.
I have created a working sample on Github and you can follow every single step by taking a look at the commit history. There you can see individual changes, starting from an empty Spring Boot application with no database to the final solution with Spring Data JPA and Flyway.
In the following sections and snippets, I will highlight the important parts of each step.