Manage H2 and Postgres in same pom.xml in Spring Boot

Hichem BOUSSETTA :

I am developing a micro-service application using Spring Boot. My application will use for production configuration a Postgres DB and for Spring Boot auto-test a H2 DB. My pom.xml includes therefore both dependencies (H2 + Postgres). I tried to associate H2 dependency with tes scope, and Postgres with runtime as following:

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

I can see when running mvn test that Spring Boot selects by default postgres database which is not present within my unit test environment. This is the reason why I prefer using H2 for running unit tests.

Is there a proper way to tell spring boot to use H2 for test and Postgres otherwise?

I don't know if using different application.properties file (one in src/main/resources and the other in src/test/resources) would solve the issue.

g00glen00b :

You should be aware that there are multiple class paths, such as:

  1. The compile-time classpath,
  2. The runtime classpath,
  3. The testing classpath.

When you use <scope>runtime</scope>, the dependency will be available in both the runtime classpath as the testing classpath, as mentioned by the documentation:

This scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.

That means that even when you're executing your tests, Postgres would still be on your classpath if you use <scope>runtime</scope>.


The solution you mentioned, by providing two separate application.properties is the right choice.

Within src/main/resources/application.properties, you could configure the datasource like this:

spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase

Within src/test/resources/application.properties, you could configure the datasource like this:

spring.datasource.url=jdbc:h2:mydatabase

If you need more fine-grained control, you can use Spring profiles. For example, you could use a profile called "testdb", and then annotate your test using @ActiveProfiles("testdb").

Now you could create a file called application-testdb.properties and add the properties you need to set up your test database.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=78591&siteId=1