This guide shows how to use
H2 as a mock database for
unit testing in
Spring Boot projects with JUnit and Spring Data JPA.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2. Configure H2 for Tests
In
application-test.properties
:
spring.datasource.url=jdbc:h2:mem:mockdb;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
This makes H2 act as a mock DB that resets after each test run.
3. Create Entity
import jakarta.persistence.*;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
}
4. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
5. Unit Test with H2
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
class UserRepositoryTest {
@Autowired
private UserRepository repo;
@Test
void testInsertAndFind() {
User user = new User();
user.setName("Alice");
user.setEmail("alice@mail.com");
repo.save(user);
User found = repo.findById(user.getId()).orElse(null);
assertThat(found).isNotNull();
assertThat(found.getEmail()).isEqualTo("alice@mail.com");
}
}
6. Run Tests
Execute:
mvn test
H2 will serve as a temporary mock database, ensuring isolated unit tests.
image quote pre code