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

Ste*_*ker 5 java spring dependency-management spring-boot

我正在尝试使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后期望它能够工作:

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

当在正常情况下运行时,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();
    }
}
Run Code Online (Sandbox Code Playgroud)

它爆炸了:

引起: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进行实际转换的 的内部,它似乎捕获ConversionServiceDefaultListableBeanFactory. 在设置该字段的位置设置一个观察点,我找到了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();
Run Code Online (Sandbox Code Playgroud)

因此,@Value注入是在ConversionService应用于之前发生的BeanFactory。不,布埃诺!

我找到了似乎是一个解决方法:

@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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我哪里出错了?春季4.3.0,春季启动1.4.0M3

编辑

现在我发现了另一种让它失败的方法!无需实现相同的配置类EnvironmentAware

@Override
public void setEnvironment(Environment environment) {
    ((AbstractEnvironment) environment).setConversionService(conversionService());
}
Run Code Online (Sandbox Code Playgroud)

我发现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)

Ste*_*ker 2

Spring Boot 开发人员已确认,该文档记录很少,并且无法按指定方式工作: https: //github.com/spring-projects/spring-boot/issues/6222