How do you mock a static method in JUnit? Is it possible without external libraries?

JUnit has no built-in support for mocking static methods; doing so requires a mocking library like Mockito, which added static mocking support via its inline mock maker starting in version 3.4.0.

Key Points

Example

To test code depending on UUID.randomUUID(), you'd use mockStatic(UUID.class) to stub the static call to return a fixed UUID instead of a random one.

try (MockedStatic<UUID> mocked = mockStatic(UUID.class)) {
    mocked.when(UUID::randomUUID).thenReturn(fixedUuid);

    assertEquals(fixedUuid, idGenerator.generate());
}

Interview Tip

A concise interview answer is

JUnit itself can't mock static methods - that requires a library like Mockito, which supports it through mockStatic() and the inline mock maker since version 3.4.0. Before that, teams relied on the heavier PowerMock library for the same capability.

Last updated: 16 July 2026

Previous question: What is the purpose of the @Test annotation?

Next question: Can you explain how @RunWith and @Rule work in JUnit?

More JUnit interview questions

All JUnit questions