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

@DataJpaTest
@SpringBootTest
@TestPropertySource(locations = "classpath:application-test.properties")
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
public class ClinicTest {
    @Resource
    private ClinicRepository clinicRepository;

    @Test
    public void givenClinic_whenSave_thenGetOk() {

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

        // the id keeps incrementing between runs
        System.out.println(clinicRepository.save(clinic).getId());
    }

}

application-test.properties

jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:testdb
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
spring.test.database.replace=none

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

Answer

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.