I am mocking Instants in my unit tests with mockito (org.mockito:mockito-core:4.7.0). The instants are mocked as expected (see screenshot).
Once I calculate the Duration of the 2 mocked Instants I get the following error:
Cannot read field "seconds" because "end" is null
I thougt that the problem is, that the whole Instant class is mocked, so I additionally passed Mockito.CALLS_REAL_METHODS so that the real implementation is used for the methods I do not mock:
val mock: MockedStatic[Instant] = mockStatic(classOf[Instant], Mockito.CALLS_REAL_METHODS)
Then I get the following error:
class org.mockito.internal.util.reflection.ReflectionMemberAccessor cannot access a member of class java.time.Instant (in module java.base) with modifiers "private static"
MyClass.scala
class ClassToTest() {
def run(): Duration = {
val now = Instant.now()
val now1 = Instant.now()
Duration.between(now1, now)
}
}
Test.scala
@Test
def test_duration(): Unit = {
val testee = new ClassToTest()
val timeMocked = Instant.parse("2022-08-31T08:55:48.200Z")
val mock: MockedStatic[Instant] = mockStatic(classOf[Instant])
try {
mock.when(() => Instant.now()).thenReturn(timeMocked)
val result = testee.run()
} finally if (mock != null) mock.close()
}
