Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Static and Final Mocking

Mocking Constructors and Time

Use Mockito's mockConstruction to replace objects created with new, then learn the cleaner alternatives: factories and java.time.Clock for deterministic time in tests.

Two things make code hard to test: objects created inside methods with new, and the current time. Mockito's inline mock maker can intercept constructors (mockConstruction) and statics (mockStatic(LocalDate.class)), but for both problems the better answer is usually a small change in design. This lesson shows the Mockito tools first, then the designs that make them unnecessary, with runnable Java for the designs.

Mockito itself does not run on this site; real Mockito code is read-only and clearly separated from the runnable examples.

mockConstruction: intercepting new

Suppose a method builds its own helper:

Java
class Exporter {
    String export(String data) {
        PdfWriter writer = new PdfWriter("out.pdf");   // hard-wired
        writer.write(data);
        return writer.path();
    }
}

With real Mockito you can replace every PdfWriter created inside a block:

Java
try (MockedConstruction<PdfWriter> created = mockConstruction(PdfWriter.class,
        (mock, context) -> when(mock.path()).thenReturn("fake.pdf"))) {

    String path = new Exporter().export("hello");

    assertEquals("fake.pdf", path);
    PdfWriter writer = created.constructed().get(0);
    verify(writer).write("hello");
    // context.arguments() holds the constructor arguments: "out.pdf"
}

What to know:

  • It returns a MockedConstruction<T> (AutoCloseable). Like mockStatic, it is thread-local and ends on close().
  • created.constructed() lists the mocks that were built.
  • The initializer lambda runs for each new instance, with a MockedConstruction.Context that gives the construction count and constructor arguments.
  • It needs the inline mock maker (default in Mockito 5).
  • It is a last resort. A test that replaces new is tied to the exact way the code is built.

The designed alternative: inject a factory

If the class receives the way to create the helper, no instrumentation is needed. The factory can be a functional interface and a lambda in tests.

Java A factory instead of mockConstruction

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 factory plays the role of mockConstruction: you see how many writers were created and what they received, but in ordinary Java.

Time: the classic hidden dependency

Code that calls LocalDate.now(), Instant.now() or System.currentTimeMillis() is non-deterministic: a test that passes today fails at midnight, on Feb 29 or in another time zone.

Mockito can do it:

Java
LocalDate fixed = LocalDate.of(2030, 1, 15);
try (MockedStatic<LocalDate> dates = mockStatic(LocalDate.class, CALLS_REAL_METHODS)) {
    dates.when(LocalDate::now).thenReturn(fixed);
    assertTrue(new Subscription().isExpired());
}

This is legal, but fragile: any library code that calls LocalDate.now() on that thread is affected, JDK classes are sensitive to instrumentation, and CALLS_REAL_METHODS is needed so LocalDate.of(...) still works.

The better answer: inject java.time.Clock

The java.time API was designed for this. Every now() method has an overload taking a Clock. Your class takes a Clock; production passes Clock.systemUTC(); tests pass Clock.fixed(...) or a movable test clock.

Java Deterministic time with Clock.fixed

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.

For code that needs time to pass during a test (timeouts, token expiry), write a tiny mutable clock:

Java A clock you can move forward

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.

With a Clock dependency, nothing needs mockStatic, and the test runs instantly instead of sleeping.

Choosing the tool

Problem Reach for first Mockito feature as fallback
new Helper() inside a method Inject a factory or the helper itself mockConstruction
LocalDate.now() and friends Inject Clock mockStatic(LocalDate.class, CALLS_REAL_METHODS)
Random values Inject Random with a seed or a Supplier mockStatic on your own wrapper
Project static helper Make it an instance or injectable function mockStatic

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What does created.constructed() return in a mockConstruction block?

    MockedConstruction records every instance built while it is open, so you can stub or verify them afterwards.
  2. 2. Which is the preferred way to make a class's use of the current date testable?

    Clock is the standard seam in java.time: Clock.fixed or a controllable clock gives deterministic results without instrumentation.
  3. 3. Why does the mockStatic example for LocalDate use CALLS_REAL_METHODS?

    Without it, every other static method of the class would return default values like null.

Summary

  • mockConstruction intercepts new inside a thread-local, closable scope and gives you the created mocks.
  • Prefer injecting a factory so tests simply hand in what the code should create.
  • For time, inject java.time.Clock; use Clock.fixed or a small mutable clock.
  • Keep mockStatic and mockConstruction as fallbacks for code you cannot change.

Next: Strict stubs and unnecessary stubbing