Spring Boot integration tests doesn't read properties files

12,861

Solution 1

You should load the application-test.properties using @PropertySource or @TestPropertySource

@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations="classpath:application-test.properties")
@ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
public class WebTests {

}

for more info: Look into this Override default Spring-Boot application.properties settings in Junit Test

Solution 2

Besides the above marked correct answer, there is another nature way to load application-test.properties: Set your test run "profile" to "test".

Mark your test cases with:

@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)

application-xxxx.properties is a naming convention for properties of different "profile".

This file application-xxxx.properties should be placed in src/main/resources folder.

"Profile" is also useful in bean configuration.

Share:
12,861
Michał Szewczyk
Author by

Michał Szewczyk

Updated on July 06, 2022

Comments

  • Michał Szewczyk
    Michał Szewczyk almost 2 years

    I would like to create integration test in which Spring Boot will read a value from .properties file using @Value annotation.
    But every time I'm running test my assertion fails because Spring is unable to read the value:

    org.junit.ComparisonFailure: 
    Expected :works!
    Actual   :${test}
    

    My test:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {WebTests.ConfigurationClass.class, WebTests.ClassToTest.class})
    public class WebTests {
        @Configuration
        @ActiveProfiles("test")
        static class ConfigurationClass {}
    
        @Component
        static class ClassToTest{
            @Value("${test}")
            private String test;
        }
    
        @Autowired
        private ClassToTest config;
    
        @Test
        public void testTransferService() {
            Assert.assertEquals(config.test, "works!");
        }
    }
    

    application-test.properties under src/main/resource package contains:

    test=works! 
    

    What can be the reason of that behavior and how can I fix it?
    Any help highly appreciated.