【发布时间】:2021-03-31 17:03:32
【问题描述】:
在使用@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 转换都将被注册和选择。
【问题讨论】:
标签: spring spring-boot kotlin junit5 spring-boot-test