正在 spring 测试中加载文件

Loading files in spring tests

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

./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 中,我从资产文件夹加载一些属性文件,如下所示:

@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 {
}

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

@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/strings.properties  

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

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