0
votes

I tried a spring boot 2.4.0 application, wrote some tests. Here's my test class

@SpringBootTest
@ActiveProfiles("test")
@TestPropertySource(locations = "classpath:application-test.properties")
public class SampleTest {
    @Test
    public void testMethod1() {
        //some logic
    }
}

I have this structure

src/
  main/
    java/
      //// further packages
    resources/
      bootstrap.yml
  test/
    resources/
      application-test.properties

Above code is picking bootstrap.yml as it contains this property spring.profiles.active=${PROFILE} Btw, this application is using spring-cloud-config

It gives this error

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'PROFILE' in value "${PROFILE}"

Why is spring-boot not picking up my test properties file? It is giving precedence to bootstrap.yml file always. Please help

2
Remove TestPropertySource and EnableConfigurationProperties - Simon Martinelli
Try the same name and extension for test properties. I mean change application-test.properties to application.yml in src/test/resource - Keshavram Kuduwa
@SimonMartinelli tried EnableConfigurationProperties, didnt work - Shades88

2 Answers

0
votes

I reproduced your example and it works if I just add this to the test class

@ActiveProfiles("test")
@SpringBootTest
class SampleTest {

You don't need any of the other annotations.

0
votes

I solved this myself with a little help from @SimonMartineli. My spring-boot 2.4.0 project uses spring-cloud-config. Hence there is bootstrap.yml. It has two properties

spring.active.profiles=${PROFILE}
spring.cloud.config.uri=${CONFIG_SERVER_URI}

These placeholders are supplied values from env variables in run-time.

Now even if I mention @TestPropertySource(locations = "classpath:application-test.properties") in my test classes, it doesnt seem to be working. Test class still tries to load bootstrap.yml fist. It used to work in spring-boot 2.1.5 from which I migrated.

To solve this I used this annotation in my test class.

@SpringBootTest(properties = {"spring.cloud.config.enabled=false", "spring.profiles.active=test"}) 
public class SampleTest {
    @Test
    public void testMethod1() {
        //some logic
    }
}

So this basically solved the other property that spring-cloud-config looks for which is that spring.profiles.active and it had a placeholder. Hope this helps someone who faces similar issue.