2017-03-21 84 views
0

使用gradle(3.4.1)和integrationTest配置,使用Spring Boot的ConfigurationProperties(1.5.1.RELEASE)進行的測試無法初始化,即使應用程序正確初始化( ./gradlew bootRun)。使用ConfigurationProperties註解的類與以下內容類似Spring Boot ConfigurationProperties無法初始化以進行集成測試

@Component 
@ConfigurationProperties(prefix = "foo") 
@Validated 
public class AppConfiguration { 
    @NonNull 
    private URL serviceUrl; 
    ... 

配置文件確實有getter和setter。所產生的誤差是類似於

java.lang.IllegalStateException: Failed to load ApplicationContext 
.... 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AppConfiguration': Could not bind properties to AppConfiguration 
.... 
Caused by: org.springframework.validation.BindException: org.springframework.boot.bind.RelaxedDataBinder$RelaxedBeanPropertyBindingResult 
Field error in object 'foo' on field 'serviceUrl': rejected value [null]; codes ... 

的配置類集成測試的被註釋如下如下

@Configuration 
@ComponentScan(...) 
@EnableConfigurationProperties 
@EnableIntegration 
public static class ContextConfiguration {} 

回答

0

測試類具有下列註釋

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration 
public class ReleaseTest { 
... 

後看着ConfigurationPropertiesBindingPostProcessor#postProcessBeforeInitialization()的Spring Boot代碼,它建議屬性源不在g發現。加入org.springframework.boot:彈簧引導起動測試工件作爲一個編譯時間依賴性,並且使用適當YAML修改測試類的上下文配置到

@ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class) 

的AppConfiguration類被初始化基於屬性的文件。

另一種方法是添加

@TestPropertySource("classpath:/application.properties") 

這種方法不需要彈簧引導啓動測試依賴,並要求「傳統」的屬性文件用於(YAML文件不會使用這種方法)。

相關問題