This guide shows how to use
H2 database in
Spring Boot for automated testing in
CI/CD pipelines.
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>
Use
<scope>test</scope> so H2 is used only during testing.
2. Configure H2
In
application-test.properties:
spring.datasource.url=jdbc:h2:mem:ci_db;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 ensures a fresh in-memory database for every test run.
3. Example Entity
@Entity
public class Employee {
@Id @GeneratedValue
private Long id;
private String name;
private String role;
}
4. Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
5. Write a Test
@SpringBootTest
class EmployeeRepositoryTest {
@Autowired
private EmployeeRepository repo;
@Test
void testSave() {
Employee emp = new Employee();
emp.setName("Alice");
emp.setRole("Developer");
repo.save(emp);
assertEquals(1, repo.findAll().size());
}
}
6. Integrate in CI/CD
- In Jenkins/GitHub Actions/GitLab CI, run:
mvn test
- H2 ensures tests run fast without external DB.
- Every pipeline execution starts with a clean DB state.
image quote pre code