Spring Boot测试用例不使用自定义转换服务

时间:2016-06-21 18:39:09

标签: java spring spring-boot dependency-management

我正在尝试使用Spring Boot Test编写集成测试用例。

我自定义ConversionService以了解新的java.time类型:

@Configuration
public class ConversionServiceConfiguration {
    @Bean
    public static ConversionService conversionService() {
        final FormattingConversionService reg = new DefaultFormattingConversionService();
        new DateTimeFormatterRegistrar().registerFormatters(reg);
        return reg;
    }
}

然后期望它起作用:

@Component
class MyServiceConfig {
    @Value("${max-watch-time:PT20s}")
    private Duration maxWatchTime = Duration.ofSeconds(20);
}

在正常SpringApplication.run下运行时,这似乎工作正常。但是,在我的测试用例中:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT, classes= {
    MyServiceMain.class,
    AttachClientRule.class
})
public class MyTest {
    @Inject
    @Rule
    public AttachClientRule client;

    @Test(expected=IllegalArgumentException.class)
    public void testBad() throws Exception {
        client.doSomethingIllegal();
    }
}
它爆炸了:

  

引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'AttachClientRule'的bean时出错:通过构造函数参数0表示的不满意依赖:

     

创建名为'MyServiceConfig'的bean时出错:通过字段'maxWatchTime'表示的不满意:无法将[java.lang.String]类型的值转换为必需类型[java.time.Duration];

     

嵌套异常是java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为必需的类型[java.time.Duration]:找不到匹配的编辑器或转换策略;

深入了解进行实际转换的TypeConverterDelegate的内容,它似乎捕获了ConversionService上字段中使用的DefaultListableBeanFactory。设置关于该字段设置位置的观察点,我找到了AbstractApplicationContext.refresh()方法:

// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();  // <--- MyServiceConfig initialized here
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory); // <--- DefaultListableBeanFactory.conversionService set here!!!
// Last step: publish corresponding event.
finishRefresh();

因此@Value注入是在ConversionService应用于BeanFactory之前发生的。没有bueno!

我发现似乎是一种解决方法:

@Configuration
public class ConversionServiceConfiguration implements BeanFactoryPostProcessor {
    @Bean
    public static ConversionService conversionService() {
        final FormattingConversionService reg = new DefaultFormattingConversionService();
        new DateTimeFormatterRegistrar().registerFormatters(reg);
        return reg;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        beanFactory.setConversionService(conversionService());
    }
}

这会强制初始化更早发生,但感觉不是正确的解决方案(至少它没有记录)。

我哪里出错了? Spring 4.3.0,Spring Boot 1.4.0M3

修改

现在我发现了另一种失败方式!没有使用相同的配置类实现EnvironmentAware

@Override
public void setEnvironment(Environment environment) {
    ((AbstractEnvironment) environment).setConversionService(conversionService());
}

我发现PropertySourcesPropertyResolver使用了错误的(默认)ConversionService。这让我很生气!

  

引起:java.lang.IllegalArgumentException:无法将值[PT15s]从源类型[String]转换为目标类型[Duration]       在org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:94)       在org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:65)       在org.springframework.core.env.AbstractPropertyResolver.getProperty(AbstractPropertyResolver.java:143)       在org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:546)       在com.mycorp.DoSomething.go(DoSomething.java:103)

2 个答案:

答案 0 :(得分:1)

Spring Boot开发人员已经确认这个文档记录不清,并且无法按照规定运行:https://github.com/spring-projects/spring-boot/issues/6222

答案 1 :(得分:0)

尝试从static bean定义中删除conversionService关键字。