Spring Boot - Configure H2 Database only for tests

43 Views Asked by At

since I'm pretty new to Java & Spring Boot and got assigned with the task of writing unit tests for an already existing project, I've wanted to ask what I'm doing wrong when trying to setup a h2 database only for the testing purposes.

pom.xml:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

Directory:

- src
  - main
    - java
    - resources
      - db.migration
        - file1.sql
        - file2.sql
        - file3.sql
        - ....sql
  - test
    - java
    - resources
      - db.migration
        - data.sql
        - schema.sql
      - application-test-db.properties

application-test-db.properties:

## H2 Test Database
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.initialization-mode=always
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql = true

spring.datasource.schema=classpath:db.migration/schema.sql
spring.datasource.data=classpath:db.migration/data.sql

Example test:

@TestPropertySource("/application-test-db.properties")
@SpringBootTest
public class textExample {
    @Test
    @DisplayName("Placeholder Test")
    public void testPlaceholder() {}
}

Problem:

When running this empty test example, I always get the error that h2 is trying to load .sql-files from the regular path: src/main/resources/db.migration/...sql. These files exist to populate the local postgres-database, but should not be called when running on of my unit tests.

Is there any way to tell h2 to not look into this folder or am I doing something fundamentally wrong here?

Thanks for your help in regard!

0

There are 0 best solutions below