【发布时间】:2020-09-27 06:46:49
【问题描述】:
例如,我有这个 Kotlin 类和方法(如果重要,请使用 Spring 管理的类):
import org.springframework.stereotype.Service
import java.time.LocalDateTime
data class TestObj(
val msg: String,
val dateTime: LocalDateTime
)
@Service
class TestAnotherService {
fun doSmthng1(testObj: TestObj) {
println("Oh my brand new object : $testObj")
}
}
@Service
class TestService(
private val testAnotherService: TestAnotherService
) {
fun doSmthng() {
testAnotherService.doSmthng1(TestObj("my message!", LocalDateTime.now()))
}
}
我如何测试TestService 通过TestObj 和dateTime 作为LocalDateTime#now?
我有几个解决方案:
- 让我们在
assertEquals的比较中添加一个小增量。 - 让我们验证在我们传入
TestAnotherService#doSmthng1dateTime字段的对象中不是null,甚至使用Mockito#any。 - 让我们使用 PowerMock 或类似工具模拟呼叫
LocalDateTime#now。 - 让我们使用 DI。使用此 bean 创建配置:
@Configuration
class AppConfig {
@Bean
fun currentDateTime(): () -> LocalDateTime {
return LocalDateTime::now
}
}
并将使用LocalDateTime#now的服务修改为:
fun doSmthng() {
testAnotherService.doSmthng1(TestObj("my message!", currentDateTimeFunc.invoke()))
}
- 别这样。这不值得测试
LocalDateTime。
哪个是最佳解决方案?或者也许还有其他解决方案?
【问题讨论】:
-
我建议你学习Writing and testing convenience methods using Java 8 Date/Time classes和How to change the value new Date() in java。它是用 Java 编写的,但我当然希望它也能在 Kotlin 中运行。
-
@OleV.V.我知道了。在这些问题中,人们建议使用 DI 或其他方式注入
Clock。谢谢!
标签: java datetime kotlin architecture software-design