Video in progress

Strong Middle 🧪 Testing

How can Mockito mock static methods and final classes, and why should you be careful with it?

Since Mockito 5, the default "inline mock maker" is used: it rewrites a class's bytecode at runtime through a Java agent. That's why final classes and mockStatic work, but a static mock applies only in the current thread and inside a try-with-resources.

📖 Answer

The old "subclass" mock maker created the mock as a subclass, and you can't extend a final class. The inline mock maker instead changes the bytecode of the existing class in place through the Instrumentation API, so both final and static can be intercepted.

try (MockedStatic<Instant> mocked = mockStatic(Instant.class)) {
    mocked.when(Instant::now).thenReturn(Instant.parse("2026-01-01T00:00:00Z"));
    assertThat(service.isExpired(token)).isTrue();
} // Instant goes back to normal here

Things to be careful about:

  • a static mock is thread-local. If the service uses CompletableFuture.supplyAsync inside, it calls the real Instant.now() on another thread;
  • if you don't close() it, the mock "leaks" into later tests;
  • on JDK 21+ there's a warning about dynamically loading the agent; it's recommended to attach Mockito as a -javaagent (through Surefire's argLine).

In fact mockStatic is often a design signal: instead of Instant.now(), inject a Clock, and instead of UUID.randomUUID(), an IdGenerator interface. Then the test gets a plain fake, and no bytecode magic is needed.