spring-bootkotlinmockito

Mockito mockStatic ZonedDateTime gives TemporalAccessor error


I have a wiremock endpoint.

From the test class I call an api method which inturn calls the wiremock endpoint.

The test class mocks the static zonedDateTime code as below:

    val now = "2025-06-13T15:00:00.000+01:00"
    val mockedDateTime = ZonedDateTime.parse(now)
    Mockito.mockStatic(ZonedDateTime::class.java).use {
      it.`when`<Any> { ZonedDateTime.now() }.thenReturn(mockedDateTime)
      // call api
    }

This code was working fine in SpringBoot 3.4 After I tried upgrading to SpringBoot 3.5 I get below error:

java.lang.NullPointerException: Cannot invoke "java.time.temporal.TemporalAccessor.getLong(java.time.temporal.TemporalField)" because "this.temporal" is null

How can I fix this issue?

I am not even sure what else I have to mock here because I don't know which TemporalField value it is expecting.


Solution

  • Can you please try below way once:

     val now = "2025-06-13T15:00:00.000+01:00"
     val mockedDateTime = ZonedDateTime.parse(now)
     val clock = Clock.fixed(mockedDateTime.toInstant(), mockedDateTime.zone)
     Mockito.mockStatic(Clock::class.java).use {
         it.`when`<Any> { Clock.systemDefaultZone() }.thenReturn(clock)
         // call api
     }
    

    Import Clock from import java.time.Clock;