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

家住魔仙堡 提交于 2021-01-29 08:52:12

问题


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()))
    }
}

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

I have several solutions:

  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
    }
}

And modify service that using LocalDateTime#now to this:

    fun doSmthng() {
        testAnotherService.doSmthng1(TestObj("my message!", currentDateTimeFunc.invoke()))
    }
  1. Just don't. This doesn't worth it to test LocalDateTime.

Which is an optimal solution? Or maybe there are other solutions?


回答1:


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.



来源:https://stackoverflow.com/questions/62259765/how-shoul-i-test-logic-that-contains-calls-to-aquire-current-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!