Spring @Value 注入转换在@SpringJUnitConfig 测试中不起作用

Spring @Value injection conversion not working in @SpringJUnitConfig test

在使用 @SpringJUnitConfig 测试时,我找不到在注入 @Value 时进行自动值转换的方法。

例如,对于给定的代码:

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

@Component
class ValueConvertInjection(@Value("2ms") val duration : java.time.Duration) {
    @PostConstruct
    fun init() = println("Duration converted: $duration")
}

给定的测试将失败:

@SpringJUnitConfig(classes = [ValueConvertInjection::class])
class JUnitValueConvertInjectionTest {
    @Autowired
    lateinit var vi :ValueConvertInjection

    @Test
    fun test() = assert(vi.duration == Duration.ofMillis(2))
    
}

但有以下例外:

...
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.time.Duration'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.Duration': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:76)
    ... 85 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.time.Duration': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:262)
    at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73)
    ... 89 more

我找不到应该添加到上下文中的内容,因此任何 Spring 转换都将被注册和选择。

要使用时长class,可以尝试如下

@Component
@ConfigurationProperties(prefix="time")
class ValueConvertInjection {
 
    Duration val = Duration.ofSeconds(60);

    @PostConstruct
    fun init() = println("Duration converted: $duration")
}

并在您的 src/test/resources 中创建 application.yml

time:
  val:
    2ms

Spring Boot用转换服务初始化context,这是你需要的:

public class ConversionConfiguration {
    @Bean
    fun conversionService() = ApplicationConversionService.getSharedInstance()
}

@SpringJUnitConfig(classes = [
        ValueConvertInjection::class,
        ConversionConfguration::class
]) {
class JUnitValueConvertInjectionTest {
    @Autowired
    lateinit var vi: ValueConvertInjection

    @Test
    fun test() = assert(vi.duration == Duration.ofMillis(2))   
}