我应该如何测试包含对获取当前日期的调用的逻辑? [英] How shoul I test logic that contains calls to aquire current date?

查看:19
本文介绍了我应该如何测试包含对获取当前日期的调用的逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个 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 是否通过 TestObjdateTime 作为 LocalDateTime#now?

How can I test that TestService passes TestObj with dateTime as LocalDateTime#now?

我有几个解决方案:

  1. 让我们在 assertEquals 的比较中添加一个小的增量.
  2. 让我们验证在我们传入的对象中 TestAnotherService#doSmthng1 dateTime 字段不是 null 甚至使用 Mockito#any.
  3. 让我们使用 PowerMock 或类似方法模拟调用 LocalDateTime#now.
  4. 让我们使用 DI.使用这个 bean 创建配置:
  1. Let's add a small delta in the comparison in the assertEquals.
  2. Let's verify that in the object that we passing in the TestAnotherService#doSmthng1 dateTime field is not null or even use Mockito#any.
  3. Let's mock call LocalDateTime#now using PowerMock or similar.
  4. 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()))
    }

  1. 别这样.这不值得测试 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆