https://kotlinlang.org logo
Title
d

Daniel Branco

09/16/2021, 2:01 PM
Hello everyone, Is it a way to mock only one static method using mockk? MockkStatic is mocking the whole LocalDateTime and we just want to mock the now
m

Mattia Tommasone

09/16/2021, 2:07 PM
yep you should be able to
mockkStatic(LocalDateTime::now)
q

Quincy

09/16/2021, 2:07 PM
Assuming you're on the JVM, have you considered using a
Clock
instead?
val clock = Clock.fixed(Instant.now(), ZoneId.of("UTC"))
val now = LocalDateTime.now(clock)
For example ^
2
You would then inject the clock into your production code so that its implementation can be replaced in tests.
This is the official recommendation in the java.time docs.
d

Daniel Branco

09/16/2021, 2:09 PM
Thanks both, let me check which approach to use with the team
@Mattia Tommasone I get this probably Clock is easier
Overload resolution ambiguity. All these functions match.
public open fun now(): LocalDateTime! defined in java.time.LocalDateTime
public open fun now(clock: Clock!): LocalDateTime! defined in java.time.LocalDateTime
public open fun now(zone: ZoneId!): LocalDateTime! defined in java.time.LocalDateTime
m

Mattia Tommasone

09/16/2021, 2:21 PM
yep makes a lot of sense, it’s probably easier to use Clock
e

Emil Kantis

09/16/2021, 3:08 PM
I usually create a
object Time { fun now() = Instant.now()}
Then it's easy to simply do mockkObject(Time)
Plus you don't have to inject a clock instance simply for testability :)
q

Quincy

09/16/2021, 5:59 PM
Injecting a clock can also help with portability concerns. I've seen issues with timetamps being created with different resolutions depending on the clock being provided by the architecture. The JDK defines
System.currentTimeMillis()
as returning a timestamp with a platform dependent resolution.
d

Daniel Branco

09/17/2021, 8:17 AM
ty all. For what we needed we just passed a Loca..now() as default value to the method and in test time we just injected. But many thanks for your alternatives, it is good to have so many answer in short time