【问题标题】:How shoul I test logic that contains calls to aquire current date?我应该如何测试包含获取当前日期的调用的逻辑?
【发布时间】: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 通过TestObjdateTime 作为LocalDateTime#now

我有几个解决方案:

  1. 让我们在assertEquals 的比较中添加一个小增量。
  2. 让我们验证在我们传入TestAnotherService#doSmthng1dateTime字段的对象中不是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

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

【问题讨论】:

标签: java datetime kotlin architecture software-design


【解决方案1】:

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

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

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

【讨论】:

  • 看起来不错,谢谢!这个选项对我来说更合适,但我们等待其他意见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-19
  • 2012-07-19
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多