Skip to content

Use H2 as test DB in JUnit5

I’m developing an app in Spring Boot. I use a PostreSQL DB for production, and I want my JUnit 5 tests to run on a H2 memory DB. Problem is, after some configuration, the tests still don’t seem to run on the in-memory db:

  • I can access entities from the prod db (a saved entity doesn’t persist in the prod db tho)

  • if I grep through the test logs, I can see that Hibernate uses org.hibernate.dialect.PostgreSQLDialect

@TestPropertySource(locations = "")
public class ClinicTest {
    private ClinicRepository clinicRepository;

    public void givenClinic_whenSave_thenGetOk() {

        var clinic = new Clinic();
        clinic.setName("asd asd");
        // the ids of prod db entities are printed
        clinicRepository.findAll().forEach(clinic1 -> System.out.println(clinic1.getId()));

        // the id keeps incrementing between runs



What should I change to run self-contained test on a H2 in memory database?


Spring, by default, creates an H2 DB for the test. You don’t need to specify it in your properties file.

Just add h2 in your pom.xml and set its scope to test. Spring Boot should handle the rest.