当 application.yml 位于另一个位置时,@Value 在 JUnit 测试期间不起作用。
FooServiceTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class })
public class FooServiceTest {
其他模块中的EmailService
public class EmailService {
@Value("${aws.credentials.accessKey}")
private String accessKey;
应用程序.yml
aws:
credentials:
accessKey: XXXXXXXX
secretKey: ZXXXXXXXXX
但是我得到了:
Could not resolve placeholder 'aws.credentials.accessKey' in string value "${aws.credentials.accessKey}"
连我都加了
-Dspring_config_location=/home/foo/other/location/config/
最佳答案
标准 Spring Boot 位置
如果你想加载spring-boot的application.properties
,你应该用Spring Boot启动单元测试(使用@SpringApplicationConfiguration
):
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { AppConfig.class })
public class FooServiceTest {
@Test
public void test...
}
application.yml
应该在类路径的 /config
或 root
下。
参见 Spring Doc :
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
- A /config subdirectory of the current directory.
- The current directory
- A classpath /config package
- The classpath root
指定其他位置(例如从单元测试执行时)
通常,您可以使用 PropertySource
,但是即使它允许从其他位置加载配置文件,它也不适用于注入(inject)的 (@Value
) 属性。
但是,您可以在静态 block 中指定 spring.config.location
环境变量:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { AppConfig.class })
public class FooServiceTest {
static {
//if the file is NOT in the classpath
System.setProperty("spring.config.location", "file:///path/to/application.yml");
//if the file is in the classpath
//System.setProperty("spring.config.location", "classpath:/path/in/classpath/application.yml");
}
@Test
public void test...
}
从 Gradle 运行测试
根据 this你可以这样做:
$ gradle test -Dspring.config.location=file:///path/to/application.yaml
或者
$ SPRING_CONFIG_LOCATION=file:///path/to/application.yaml gradle test
或者添加一个任务来定义系统属性:
task extconfig {
run { systemProperty "spring.config.location", "file:///path/to/application.yaml" }
}
test.mustRunAfter extconfig
关于SpringBoot - @Value 在自定义 Spring 配置位置的 JUnit 测试期间不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368640/