SpringBoot - @Value 在自定义 Spring 配置位置的 JUnit 测试期间不起作用

标签 spring gradle spring-boot

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 应该在类路径的 /configroot 下。

参见 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/

相关文章:

java - [JAVA Spring SOAP WSDL]

java - 如何列出Spring Boot中所有托管的@Component?

android - java.lang.NoClassDefFoundError : org. 乔达.time.DateTime

java - Spring oauth2 sso 示例不起作用

java - 使用 Spring 的 JDBCTemplate 对内存数据库进行 Jersey e2e 集成测试

java - 使用 Spring mockMvc 测试可选路径变量

gradle - 如何在使用 Gradle 构建 fat jar 时编译不同的口味

java - 包括来自同级 gradle 模块的 FindBugs 分析所需的文件

java - 如何在 Jackson xml 解析器中将八位字节流解析为 json?

java - 如何在 Spring Boot 1.4 中自定义 Jackson