3

I am trying to test my Spring Configuration. Here is my config class

@Configuration
@PropertySource("/etc/my.properties")
@ComponentScan("my.package")
public class SpringConfig {

    @Bean
    .....
}

And when I tried to test it thru my test as

@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations = "classpath:test.properties")
@ContextConfiguration(classes = {SpringConfigIntTest.class, SpringConfig.class})
public class SpringConfigIntTest {
    .......
}

I keep getting the failure saying /etc/my.properties cannot be found. But I think I have overridden it with test.properties and I have been googling around without seeing other people doing it differently.

I am using spring-context, spring-beans, spring-core 4.2.2, and spring-test 4.2.4. Can someone please give me some help here? Deeply appreciate it

gigi2
  • 1,996
  • 1
  • 17
  • 22
  • I think I should be more specific that due to the file not found failure, SpingConfig cannot be initialized in my unit test. That is what confuses me, in the debug output from Spring when running test, it does say '....contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{classpath:test.properties}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader' – gigi2 Nov 10 '16 at 19:55
  • 1
    Try replacing `@ContextConfiguration(classes = {SpringConfigIntTest.class, SpringConfig.class})` with @SpringBootTest(classes = SpringConfigIntTest.class). Here is my another answer with examples to a similar question, which will be of some help. http://stackoverflow.com/questions/39823045/unable-to-inject-dependency-in-junit-test/39823196#39823196 – Minjun Yu Nov 10 '16 at 20:11

1 Answers1

1

You can set the property source to not fail if the resource does not exist:

@PropertySource(value = "/etc/my.properties", ignoreResourceNotFound = true)
David Siro
  • 1,826
  • 14
  • 33