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?