This guide shows how to use
H2 database for running
integration tests in
Spring Boot, ensuring fast and isolated test runs.
1. Add Dependencies
In
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
Using
<scope>test</scope> ensures H2 is only used for tests.
2. Configure H2
In
src/test/resources/application-test.properties:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
3. Example Entity
@Entity
public class User {
@Id @GeneratedValue
private Long id;
private String name;
}
4. Repository
public interface UserRepository extends JpaRepository<User, Long> {}
5. Write Integration Test
@SpringBootTest
@TestPropertySource(locations = "classpath:application-test.properties")
class UserRepositoryIT {
@Autowired private UserRepository repo;
@Test
void testSaveAndFind() {
User u = new User();
u.setName("Alice");
repo.save(u);
assertEquals(1, repo.findAll().size());
}
}
6. Run Tests
Execute:
mvn test
The app starts with H2 in-memory DB, runs integration tests, and cleans up after.
image quote pre code