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: • Plain JUnit only provides test structure and assertions - it has no concept of mocking at all. • Mockito's mockStatic(SomeClass.class) inside a try-with-resources block lets you stub static method calls for the duration of that block. • Before Mockito 3.4.0, mocking static methods required alternative tools like PowerMock, which is heavier and less actively maintained now. • Static mocking should be scoped as narrowly as possible, since it changes global class behavior for the duration of the mock. • Frequent need to mock statics is often a sign the static call should be wrapped in an injectable instance method instead.
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.
Code Example:
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."