Hello everyone, Is it a way to mock only one static method using mockk? MockkStatic is mocking the ...
d
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
yep you should be able to
mockkStatic(LocalDateTime::now)
q
Assuming you're on the JVM, have you considered using a
Clock
instead?
Copy code
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
Thanks both, let me check which approach to use with the team
@Mattia Tommasone I get this probably Clock is easier
Copy code
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
yep makes a lot of sense, it’s probably easier to use Clock
e
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
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
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
483 Views