How to Use H2 Database for Testing Spring Boot Applications
To use
H2 for testing in Spring Boot, add the spring-boot-starter-test and com.h2database:h2 dependencies, then configure your test to use the in-memory H2 database by setting spring.datasource.url=jdbc:h2:mem:testdb. This allows fast, isolated tests without needing an external database.Syntax
To use H2 for testing in Spring Boot, you need to add dependencies and configure the datasource URL for tests.
- Dependency: Add
com.h2database:h2to yourpom.xmlorbuild.gradle. - Datasource URL: Use
jdbc:h2:mem:testdbto create an in-memory database. - Test Configuration: Use
@SpringBootTestand optionally@AutoConfigureTestDatabaseto replace your main database with H2 during tests.
xml/java/properties
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency> # application-test.properties spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect // Test class example @SpringBootTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY) public class MyRepositoryTest { // test methods }
Example
This example shows a Spring Boot test using H2 in-memory database to test a simple repository.
java
package com.example.demo; 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.context.SpringBootTest; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import org.springframework.data.jpa.repository.JpaRepository; @SpringBootTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY) public class UserRepositoryTest { @Autowired private UserRepository userRepository; @Test public void testSaveAndFind() { User user = new User(); user.setName("Alice"); userRepository.save(user); List<User> users = userRepository.findAll(); assertThat(users).hasSize(1); assertThat(users.get(0).getName()).isEqualTo("Alice"); } } // User entity @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; // getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // UserRepository interface public interface UserRepository extends JpaRepository<User, Long> {}
Output
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
Common Pitfalls
Common mistakes when using H2 for Spring Boot testing include:
- Not adding the H2 dependency in the
testscope, causing runtime errors. - Forgetting to configure the datasource URL to use the in-memory database, so tests connect to the real database.
- Not using
@AutoConfigureTestDatabaseor overriding datasource properties, which prevents Spring Boot from switching to H2 during tests. - Using incompatible Hibernate dialects, which can cause schema generation errors.
java
/* Wrong: No H2 dependency and no test datasource config */ @SpringBootTest public class MyTest { // This will try to connect to the real database } /* Right: Add H2 dependency and configure test datasource */ @SpringBootTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY) public class MyTest { // Uses H2 in-memory database }
Quick Reference
Summary tips for using H2 in Spring Boot tests:
- Add
com.h2database:h2dependency withtestscope. - Set
spring.datasource.url=jdbc:h2:mem:testdbinapplication-test.properties. - Use
@AutoConfigureTestDatabaseto replace your main database during tests. - Use
spring.jpa.database-platform=org.hibernate.dialect.H2Dialectfor Hibernate compatibility. - Run tests with
@SpringBootTestto load full context.
Key Takeaways
Add the H2 dependency with test scope to your project to enable in-memory testing.
Configure your test datasource URL to jdbc:h2:mem:testdb for fast, isolated tests.
Use @AutoConfigureTestDatabase to automatically switch to H2 during tests.
Set the correct Hibernate dialect for H2 to avoid schema issues.
Always verify your tests run against H2 and not your production database.