Skip to content
Advertisement

MockitoException when trying to mock java.lang.System

I have a test case that mock a static method of java.lang.System class:

@Test
fun `getLocalTime()`() {
    // Arrange
    val staticMock = Mockito.mockStatic(System::class.java)
    Mockito.`when`(System.currentTimeMillis()).thenReturn(1000L)

    // Action
    val res = deviceTimeProvider.getLocalTime()

    // Assert
    Truth.assertThat(res).isEqualTo(1000L)

    staticMock.close()
}

But when I run the test, I got this error:

org.mockito.exceptions.base.MockitoException: It is not possible to mock static methods of java.lang.System to avoid interfering with class loading what leads to infinite loops

Why does this happen? How can I mock methods of java.lang.System class?

Advertisement

Answer

While Mockito since 3.4.0 version allows mocking static methods it is not allowed to mock the Thread and System static methods, see this comment on github

Finally note that Mockito forbids mocking the static methods of System (and Thread). Those methods are to much cemented into class loading which happens in the same thread. At some point, we might add instrumentation to class loading to temporarily disable the static mocks within it to make mocking these classes, too, where we also would need to disable their intensification properties. You can however easily mock Instant.now().

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement