由于配置负载失败,Spring Boot中的测试执行失败

时间:2016-09-27 15:14:18

标签: unit-testing spring-boot

我正在尝试测试我的应用程序并遇到麻烦:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MainConfiguration.class)
public class ProductionDataRestClientTest {

    @Test
    public void testGetProductionDataAsync() {

    }

}

MainConfiguration类如下:

@Data
@Configuration
@Slf4j
@PropertySource(value = {
        "classpath:/conf/application.properties", "classpath:/conf/application.build.properties",
        "file:${configPath}/application.properties" }, ignoreResourceNotFound = true)
public class MainConfiguration {

    @Value("${app.configName}")
    private String  configName;

    @Value("${project.name}")
    private String  appName;

    @Value("${project.version}")
    private String  appVersion;

    @Value("${app.historySize}")
    private int     historySize;

    @Value("${app.processOnlyVisibleEnvironments}")
    private Boolean processOnlyVisibleEnvironments;

    @PostConstruct
    private void logConfig() {
        appName = WordUtils.capitalize(appName);
        log.info("constructed config: " + configName);
        log.info(this.toString());
    }
}

application.properties文件在这里:

app.configName=Internal Classpath
app.historySize=25
app.processOnlyVisibleEnvironments=true

client.timeout.connect=30000
client.timeout.read=30000

threading.pool.size.environmentProcessing=5
threading.pool.size.webServiceRequesting=10

我的问题是,Spring似乎没有像正常执行那样解析值标识符,因此引发了以下的栈跟踪:

Caused by: java.lang.NumberFormatException: For input string: "${app.historySize}"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:569)
    at java.lang.Integer.valueOf(Integer.java:766)
    at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:194)
    at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:113)
    at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:464)
    at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:437)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:195)
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:125)
    at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61)
    ... 47 more

我没有任何线索,我尝试了许多不同的东西,没有任何效果。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

有一种非常简单的方法可以解决这个问题:

// To resolve ${} in @Value
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
}

这必须是加载的配置文件的方法,并有助于解析占位符。

感谢您的帮助;)