我应该如何测试包含对获取当前日期的调用的逻辑? [英] How shoul I test logic that contains calls to aquire current date?
问题描述
例如,我有这个 Kotlin 类和方法(Spring 管理的类,如果重要的话):
For example, I have this Kotlin class and method (Spring-managed class if it matters):
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
?
How can I test that TestService
passes TestObj
with dateTime
as LocalDateTime#now
?
我有几个解决方案:
- 让我们在
assertEquals
的比较中添加一个小的增量. - 让我们验证在我们传入的对象中
TestAnotherService#doSmthng1
dateTime
字段不是null
甚至使用Mockito#any
. - 让我们使用 PowerMock 或类似方法模拟调用
LocalDateTime#now
. - 让我们使用 DI.使用这个 bean 创建配置:
- Let's add a small delta in the comparison in the
assertEquals
. - Let's verify that in the object that we passing in the
TestAnotherService#doSmthng1
dateTime
field is notnull
or even useMockito#any
. - Let's mock call
LocalDateTime#now
using PowerMock or similar. - Let's use DI. Create configuration with this bean:
@Configuration
class AppConfig {
@Bean
fun currentDateTime(): () -> LocalDateTime {
return LocalDateTime::now
}
}
并将使用 LocalDateTime#now
的服务修改为:
And modify service that using LocalDateTime#now
to this:
fun doSmthng() {
testAnotherService.doSmthng1(TestObj("my message!", currentDateTimeFunc.invoke()))
}
- 别这样.这不值得测试
LocalDateTime
.
哪个是最优解?或者也许还有其他解决方案?
Which is an optimal solution? Or maybe there are other solutions?
推荐答案
您可以简单地将当前日期作为函数参数传递.
You can simply pass the current date as function parameter.
fun doSmthng(now: LocalDateTime = LocalDateTime.now()) {
testAnotherService.doSmthng1(TestObj("my message!", now))
}
在测试中,您可以传递某个特定日期并对其进行断言.想法是注入依赖而不是在函数体中显式创建.
And in the test you can pass some specific date and assert on it. Idea is to inject the dependencies instead of creating explicitly in the function body.
这篇关于我应该如何测试包含对获取当前日期的调用的逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!