简体   繁体   中英

Spring Boot profile properties doesn't work with tests

Spring Boot version 2.2.6. I have case that there is several application-{profile}.yml files in folder src/main/resources/ and I want't to build project with Maven eg mvn clean package -Dspring.profiles.active=dev

Then I have just application.yml file in folder src/test/resources , this should be a properties file to all test (IT/unit).

Now when I build with command mvn clean package -Dspring.profiles.active=dev , properties src/main/resources/application-dev.yml and src/test/resources/application.yml are MERGED and used for the tests. Well in test properties there might be pretty fatal confs eg Hibernate auto-ddl: create-drop.

Have been reading docs but I don't find any logic why properties files are MERGED in this case. Is there any good practice that tests can be forced to use ALWAYS certain properties file? I think that just using some annotations in test files isn't the best practice, eg @TestPropertySource or @ActiveProfiles , cause when you forgot to use these annotations then the case is same again. Is there some global configuration for all tests or some other better solutions?

The application.yml file has higher precedence over any environment-specific file, for example, application-dev.yml file. The standard inheritance applies, so you can override the parent properties in the profile-specific YAML file.

application.yml

server:
  port: 9090

spring:
  jpa:
    hibernate:
      ddl-auto: create-drop

application-dev.yml

spring:
  jpa:
    hibernate:
      ddl-auto: none

In case you run with the dev profile, the value of spring.jpa.hibernate.ddl-auto parameter would be none .

I get that application.yml has higher precedence in folder /src/main, but that it takes over also from folder /src/test is kinda weird.

Yes that config can be made into profile-specific files (ddl-auto: none), tough I still have problem with datasource, somehow Spring Boot is picking application-dev.ymls datasource into tests also, this is working like other way around than that ddl-auto attribute.

src/test/resources/application.yml

spring:
  datasource:
    url: jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL

src/main/resources/application-dev.yml

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/db

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM