Search code examples
javaspringjunitspring-boot

@TestPropertySource doesn't work for JUnit test with AnnotationConfigContextLoader in Spring 1.2.6


It doesn't seem that anything I do in Spring 4.1.17 with Spring Boot 1.2.6.RELEASE works at all. I just want to access the application properties and override them with test if necessary (without using the hack to inject a PropertySource manually)

this doesn't work..

@TestPropertySource(properties = {"elastic.index=test_index"})

nor does this..

@TestPropertySource(locations = "/classpath:document.properties")

nor this..

@PropertySource("classpath:/document.properties")

full test case..

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
@TestPropertySource(properties = {"elastic.index=test_index"})
public class PropertyTests {
    @Value("${elastic.index}")
    String index;

    @Configuration
    @TestPropertySource(properties = {"elastic.index=test_index"})
    static class ContextConfiguration {
    }

    @Test
    public void wtf() {
        assertEquals("test_index", index);
    }
}

resulting in

org.junit.ComparisonFailure: 
Expected :test_index
Actual   :${elastic.index}

It seems there is a lot of conflicting information between 3.x and 4.x and I can't find anything that will work for sure.

Any insight would be gratefully appreciated. Cheers!


Solution

  • Your use of @Value requires a PropertySourcesPlaceholderConfigurer bean to resolve ${...} placeholders. See the accepted answer here: @Value not set via Java-configured test context