在春季测试中加载文件

时间:2017-01-19 22:14:56

标签: java spring spring-boot properties spring-test

我在项目中的文件夹结构是:

./assets/strings.properties
./module1/src/main/java/{some-packages}/ContextConfig.java
./module1/src/test/java/{some-packages}/TestContextConfig.java
./module1/pom.xml
./module2/pom.xml
./pom.xml
在ContextConfig中的

我从assets文件夹加载一些属性文件,如下所示:

@PropertySources({
        @PropertySource("file:assets/strings.properties")
})
public class ContextConfig {
/*some code...*/
}

请注意,我没有使用classpath:,而是file:

在TestContextConfig中我导入了ContextConfig,并且我也是这样激活嵌入式mongo:

@Configuration
@Import({
        ContextConfig.class,
        MongoAutoConfiguration.class
})
public class TestContextConfig {
}

当我尝试在我的测试类中使用它时:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestContextConfig.class)
public class ProofOfConcept {
/*some code...*/
}

我得到FileNotFoundException,因为它找不到属性文件,但是当应用程序正常启动时(而不是在测试中),一切都运行良好。 我得到的例外:

Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [{some-packages}.config.TestContextConfig]; nested exception is java.io.FileNotFoundException: assets\strings.properties (System nie może odnaleźć określonej ścieżki)
    at org.springframework.context.annotation.ConfigurationClassParser.processImports(ConfigurationClassParser.java:495)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:276)

如何在测试中从assets文件夹加载文件?

1 个答案:

答案 0 :(得分:1)

属性文件 -

./assets/strings.properties  

似乎超出了您的测试环境。您将需要使用将为您的应用程序加载外部属性文件的技术。

请查看Spring application context external properties?。这应该可以解决您的问题。您可以将属性文件位置提供为VM争论,也可以在测试中进行硬编码。使用VM argurments提供此属性是首选方法。