问题
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:
- 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#doSmthng1dateTimefield is notnullor even useMockito#any. - Let's mock call
LocalDateTime#nowusing PowerMock or similar. - 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()))
}
- 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