Member-only story
How To Test Databases Easily in a Spring Boot Application
Testing techniques with embedded databases and Testcontainers library
Databases are a crucial back-end point of almost any application. Writing good tests helps us check whether the database functionality works as expected before going to production. Fortunately, there are convenient tools that assist us in this task.
In this tutorial, I’m going to show you two ways of testing databases in a Spring Boot application:
- Using the H2 in-memory/embedded database.
- Using the Testcontainers library.
You’ll understand the pros and cons of each approach. This will help you make the right decisions when choosing a tool for your database testing.
Let’s get started!
H2 Embedded Database
H2 is a lightweight open-source database based on Java. It provides developers with a quick way to configure and run a database in memory. This way, the data will not be persisted in a real database. It supports multiple SQL compatibility modes, such as IBM DB2, Apache Derby, HSQLDB, MS SQL Server, MySQL, Oracle, and PostgreSQL.
To demonstrate the usage of H2, we’ll create a simple Spring Boot application with a single JPA repository to retrieve users.
In this example, I’m using Maven as a build tool. Create a new Maven project in your favorite IDE, and put the following dependencies in the auto-generated pom.xml
file:
Create a new Java class called User
:
Note that I’m using the Lombok
library to get rid of any boilerplate code, such as getters, setters, etc.