我应该如何测试包含获取当前日期的调用的逻辑?

How shoul I test logic that contains calls to aquire current date?

例如,我有这个 Kotlin class 和方法(Spring-managed class 如果重要的话):

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 通过 TestObjdateTime 作为 LocalDateTime#now

我有几个解决方案:

  1. 让我们在 assertEquals 的比较中添加一个小的增量。
  2. 让我们验证一下我们传入的对象中的 TestAnotherService#doSmthng1 dateTime 字段不是 null 甚至使用 Mockito#any.
  3. 让我们使用 PowerMock 或类似工具模拟调用 LocalDateTime#now
  4. 让我们使用 DI。使用此 bean 创建配置:
@Configuration
class AppConfig {

    @Bean
    fun currentDateTime(): () -> LocalDateTime {
        return LocalDateTime::now
    }
}

并将使用LocalDateTime#now的服务修改为:

    fun doSmthng() {
        testAnotherService.doSmthng1(TestObj("my message!", currentDateTimeFunc.invoke()))
    }
  1. 只是不要。这不值得测试 LocalDateTime.

哪个是最优解?或者也许还有其他解决方案?

您可以简单地将当前日期作为函数参数传递。

fun doSmthng(now: LocalDateTime = LocalDateTime.now()) {
    testAnotherService.doSmthng1(TestObj("my message!", now))
}

并且在测试中您可以传递一些特定的日期并对其进行断言。想法是注入依赖项而不是在函数体中显式创建。