A Comprehensive Guide to Using H2 In-Memory Database in Unit Tests

A Comprehensive Guide to Using H2 In-Memory Database in Unit Tests
Photo by Daniel Hehn / Unsplash


Unit testing is an integral part of software development, ensuring that individual components of an application function as expected in isolation. When testing components that interact with databases, using an in-memory database is a common approach to achieve fast and reliable tests. In this guide, we'll explore how to use the H2 in-memory database in your unit tests with Spring Boot.

Step 1: Add H2 Dependency

First, ensure that you have the H2 database dependency added to your Maven or Gradle build file. In a Spring Boot project, you typically include H2 as a test dependency.



Step 2: Configure Spring Boot Application

In your Spring Boot application configuration, configure the datasource to use the H2 in-memory database. This can be achieved by specifying the JDBC URL, username, and password in the application.properties or application.yml file.

Example application.properties:


Step 3: Write Unit Tests

Write your unit tests using a testing framework such as JUnit or TestNG. Use the Spring TestContext Framework to initialize the Spring application context and enable transaction management for your tests.

Example unit test with JUnit 5:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

class UserRepositoryIntegrationTest {

    private UserRepository userRepository;

    void testSaveUser() {
        // Write your test logic here

Step 4: Run Unit Tests

Run your unit tests using your preferred build tool (Maven or Gradle) or within your IDE. The tests will utilize the H2 in-memory database configured for testing purposes.


Using the H2 in-memory database in unit tests offers a lightweight and efficient way to test database interactions in your Spring Boot applications. By following the steps outlined in this guide, you can seamlessly integrate H2 into your unit testing workflow, ensuring the reliability and effectiveness of your tests while maintaining fast execution times. Happy testing!

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.