How do you mock static methods in Mockito?

Mockito can mock static methods using the mockito-inline extension (bundled by default since Mockito 5) via the try-with-resources MockedStatic API.

Key Points: • Open a static mock scope with try (MockedStatic<Utils> mocked = mockStatic(Utils.class)) { ... }. • Inside the block, stub static calls with mocked.when(Utils::someMethod).thenReturn(value). • The mock is only active within the try block and is automatically closed (and static behavior restored) afterward. • This requires the mockito-inline artifact (or Mockito 5+, where inline mocking is the default mock maker). • Frequent static mocking often signals that the static dependency should be wrapped behind an injectable interface instead.

Example: To test code calling LocalDate.now(), you can mock the static method so the test always sees a fixed date instead of the real current date.

Code Example:

try (MockedStatic<LocalDate> mocked = mockStatic(LocalDate.class)) {
    mocked.when(LocalDate::now).thenReturn(LocalDate.of(2024, 1, 1));

    assertEquals(LocalDate.of(2024, 1, 1), reportService.today());
}

Interview Tip: A concise interview answer is:

"Since Mockito 3.4 you can mock static methods with mockStatic() inside a try-with-resources block, stubbing calls with mocked.when(ClassName::method).thenReturn(value). It requires the inline mock maker, and I use it sparingly since heavy static usage is usually better refactored to be injectable."