Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Static and Final Mocking

Mocking Static Methods

Learn how Mockito's mockStatic works with try-with-resources and thread scope, when it is justified, and how a seam or wrapper often makes the test simpler.

Static methods are hard to replace: there is no object to swap out. Code like UUID.randomUUID(), LocalDate.now() or a project helper such as Config.get("mode") is called directly, so a test cannot easily control it. Mockito can intercept static calls with mockStatic, which works through the inline mock maker. This lesson shows the real API, explains its scope rules, and runs a stand-in that behaves the same way.

Mockito is not installed on this site. Real Mockito code is read-only. The runnable examples use a hand-written, labelled stand-in (a scoped override of a static method) so you can observe the same lifecycle.

The real API

Java
import static org.mockito.Mockito.*;

class Ids {
    static String next() { return UUID.randomUUID().toString(); }
}

@Test
void orderGetsTheNextId() {
    try (MockedStatic<Ids> ids = mockStatic(Ids.class)) {
        ids.when(Ids::next).thenReturn("id-1", "id-2");

        assertEquals("id-1", Ids.next());
        assertEquals("id-2", Ids.next());

        ids.verify(Ids::next, times(2));
    }
    // Outside the block, Ids.next() is real again.
}

Key points:

  • mockStatic(Class) returns a MockedStatic<T>, which is AutoCloseable. Always put it in try-with-resources, or in a JUnit @BeforeEach with a matching close in @AfterEach.
  • It is thread-local: only the thread that created it sees the static mock. Other threads call the real method.
  • You can only have one static mock of a given class registered per thread at a time. Opening a second one throws an exception.
  • After close(), the original behavior is restored.
  • Stubbing syntax takes a lambda or method reference: ids.when(() -> Ids.parse("x")).thenReturn(5).

Partial static mocks keep real behavior for anything you do not stub:

Java
try (MockedStatic<Ids> ids = mockStatic(Ids.class, CALLS_REAL_METHODS)) {
    ids.when(Ids::next).thenReturn("fixed");
    // other static methods of Ids still run for real
}

Seeing the lifecycle (stand-in)

The program below has a static method that is overridable inside a scope. Seam.scope(...) returns an AutoCloseable, just like MockedStatic. The override is stored per thread.

Java A scoped, thread-local static override

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The three behaviors you must remember appear in the output: values come from the scope while it is open, a different thread is not affected, and everything returns to normal after close().

Why scope matters

If you forget to close a static mock, the next test in the same thread still sees the fake. This produces the worst kind of failure: tests that pass alone and fail in a suite. Two safe patterns:

Java
// Pattern 1: try-with-resources inside the test (best, scope is obvious)
@Test
void test() {
    try (MockedStatic<Ids> ids = mockStatic(Ids.class)) { ... }
}

// Pattern 2: fields closed in a lifecycle method
private MockedStatic<Ids> ids;

@BeforeEach void open()  { ids = mockStatic(Ids.class); }
@AfterEach  void close() { ids.close(); }

When mockStatic is justified

  • Legacy code that calls static helpers you cannot change yet.
  • Third-party statics (a vendor's Analytics.track(...)) that are not under your control.
  • A safety net while you refactor toward injectable dependencies.

When a seam is better

For code you own, make the static call injectable. The test becomes plain Java with no instrumentation, no thread rules and no cleanup:

Java Replace the static call with an injected supplier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This is the same technique you will use for time in Mocking constructors and time.

Common errors

Symptom Cause
Exception saying a static mock is already registered You opened a second mockStatic of the same class in the same thread without closing the first
Static mock has no effect Code runs in another thread (thread pool, parallel stream)
Mockito says the class cannot be mocked It is one of the JDK core types, or the inline mock maker is unavailable
Tests pass alone, fail together A static mock was not closed

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why should mockStatic be used in try-with-resources?

    The static mock stays active for the thread until it is closed. Not closing it leaks fake behavior into later tests.
  2. 2. Code under test runs the static call on a worker thread. What does a MockedStatic created on the test thread do there?

    Static mocks are scoped to the creating thread. Other threads execute the real method.
  3. 3. What is usually the cleaner solution for static code that you own?

    Injection needs no instrumentation, has no thread-scope pitfalls and works with any test tool.

Summary

  • mockStatic(X.class) returns an AutoCloseable MockedStatic<X>; stub with when(X::method) and verify with verify(X::method).
  • The mock is thread-local, single per class per thread, and ends on close().
  • Use it for legacy and third-party statics; prefer injection for your own code.
  • Always close in the same test or in @AfterEach.

Next: Mocking constructors and time