简体   繁体   中英

How do I set the default Spring Boot profile for running tests (without using environment variables)?

I have a Spring Boot project, using gradle, with three Spring profiles:

  • "development" (for when I'm developing)
  • "test" (for when I'm running tests)
  • "production" (for when it is deployed in production [to heroku])

I therefore have four application*.yml files:

  • application.yml (contains all the shared defaults)
  • application-development.yml
  • application-test.yml
  • application-production.yml

These environments all work fine. The problem is that when I deploy the code to heroku, heroku runs 'gradle build' (which in turn runs 'gradle test'), and heroku does not have an option of setting an environment variable. Therefore I cannot set an active profile. So when it runs the tests it is using application.yml without the overrides in application-test.yml. So therefore the tests obviously fail.

My only solution so far is to put all the application-test.yml defaults into application.yml, and then override them again in the other profiles, but this is obviously far from ideal.

Is there a way to:

  • set the active Spring profile from within gradle (note that I don't have edit access to the 'test' or 'build' tasks as they come from the 'spring boot gradle plugin')?
  • or is there a way in Spring Boot to set the default active Spring profile when tests are run?

Think joshiste's answer is the correct one.

Anyway I'd guess you also could set the SPRING_PROFILES_ACTIVE environment variable like so:

 $ heroku config:set SPRING_PROFILES_ACTIVE=test
 Adding config vars and restarting myapp... done, v12
 SPRING_PROFILES_ACTIVE: test

 $ heroku config
 SPRING_PROFILES_ACTIVE: test

 $ heroku config:get SPRING_PROFILES_ACTIVE
 test

 $ heroku config:unset SPRING_PROFILES_ACTIVE
 Unsetting SPRING_PROFILES_ACTIVE and restarting myapp... done, v13

In case you are using the @WebIntegrationTest or @IntegrationTest you can set the profiles as property value with the annotation.

Looks like this:

@RunWith(SpringJUnit4ClassRunner.class)
@WebIntegrationTest({"spring.profiles.active=test"})
public class MyWebIntegrationTests {
    // ...
} 

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