gojoGS
gojoGS

Reputation: 39

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:

@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?

Upvotes: 1

Views: 8504

Answers (2)

Steven-maina
Steven-maina

Reputation: 1

Your application-test.proprties does not have user and pasword try adding this:

#--------------------- DB Connection ------------------
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=

#--------------------JPA-ORM Properties-----------------
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.format_sql=true

Upvotes: 0

Mehdi
Mehdi

Reputation: 1096

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.

Upvotes: 4

Related Questions