Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 37 ยท Getting Started

How Mocks Work Inside

Understand what happens when you call mock(): generated classes, call interception, the stubbing registry and why constructors do not run.

Mockito can feel like magic: you write when(repo.find(1)).thenReturn(user) and a call on an object that does not exist in your source code returns the right thing. Knowing the mechanism removes the mystery and explains the rules that otherwise look arbitrary, such as "you cannot stub a final method on an old Mockito" or "matchers must be used for all arguments or none". In this lesson you build the core of a mock yourself in a few lines of plain Java.

The life of a mock call

A mock is an object of a generated class. Every method of that class is wired to the same piece of code, an interceptor. When your code calls mock.priceOf("A1"), this happens:

  1. The interceptor receives the method (priceOf) and the arguments ("A1").
  2. It records the invocation in the mock's history, so verify can find it later.
  3. It looks through the mock's stubbings for one that matches this method and these arguments.
  4. If it finds one, it produces that answer: returns the value, throws the exception or runs your Answer.
  5. If it finds none, it returns the default answer for the return type.
flowchart LR
    A["Your code calls<br/>mock.priceOf(A1)"] --> B["Generated mock class"]
    B --> C["Interceptor"]
    C --> D["Record invocation"]
    D --> E{"Matching stubbing?"}
    E -- yes --> F["Return / throw / answer"]
    E -- no --> G["Default answer<br/>0, null, empty list..."]

Every call on a mock goes through the same interceptor. Verification later reads the recorded history.

Step 1: intercept calls with a proxy

For interfaces the JDK itself can generate the class. java.lang.reflect.Proxy.newProxyInstance takes the interface and an InvocationHandler, which is your interceptor. The handler below only logs what it sees and answers with a made-up value:

Java An interceptor that logs every call

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.

There is no Calculator implementation anywhere in this program, yet calc.add(2, 3) returns something. The class was generated at run time, and every call went through the lambda.

Step 2: add stubbing and verification

Now add the other half: a table of stubbings and a history to query. This is a deliberately tiny mock framework with its own API names (Fake, answer, timesCalled), so you can see the moving parts without the rest of the Mini library:

Java A 25-line mock in plain Java

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.

That is the whole idea of Mockito in miniature. Real Mockito adds argument matchers, Answer objects, strictness checks, annotation support and good error messages on top, but the skeleton is this table plus this history.

What real Mockito does differently

  • Bytecode generation instead of Proxy. Mockito uses Byte Buddy to generate classes, so it can mock classes and not just interfaces. With the default inline mock maker it also patches the target class's own methods at load time, which is why final classes and methods work.
  • Objenesis instead of constructors. To create a mock of a class, Mockito uses a trick (the Objenesis library) that instantiates the class without calling any constructor. Field initializers do not run either, so the fields of a mock hold null, 0 and false no matter what the real class assigns. This is why mocking a class with a constructor that talks to a database is safe.
  • Thread-local bookkeeping. when(mock.call()) works because the mock call just before it has been stored in a per-thread "ongoing stubbing" slot. when(x) receives only the return value, which it ignores; the slot tells it which call to stub. The same slot explains why you cannot split matchers and raw values freely: matchers are queued in a per-thread stack until the next mock call consumes them (see Argument Matchers and Matcher Rules).
  • Stubs that are consulted newest first. If two stubbings match, the most recently defined one wins. This is why you can override a general stub with a specific one by stubbing it afterwards.

The when(...) trick

Read when(prices.priceOf("A1")).thenReturn(10.0) from the inside out. First prices.priceOf("A1") runs as a normal call on the mock: it is recorded, and the interceptor notes "this was the last call". The default answer (0.0) comes back and is passed to when, which ignores the number, picks up the remembered call and returns an object whose thenReturn registers the answer for it. Mockito also deletes that setup call from the history, so stubbing never counts as a real interaction.

Why this matters in practice

Behavior you notice The reason
Unstubbed methods return 0, null or empty collections The default answer in step 5
Stubbing a method that throws an exception inside when(...) is awkward The real-looking call runs the interceptor first; this is why doThrow(...).when(mock) exists for void methods
Field values of a mocked class are all null The constructor and initializers never ran (Objenesis)
Final classes cannot be mocked on very old Mockito The subclass mock maker cannot subclass final classes; the inline mock maker can
verify(mock).method() finds calls The interceptor stored them in step 2

Because a mock is a generated object whose methods are all intercepted, never rely on a mock's toString, equals or hashCode for logic in your test. Mockito gives them sensible defaults, and stubbing them is not supported.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the interceptor of a mock do for every call?

    Every call is recorded for verification, then answered from a matching stubbing or from the default answer.
  2. 2. Why are the fields of a mocked class instance all null, 0 or false?

    Mockito uses Objenesis to instantiate the class without calling a constructor, so initializers never run.
  3. 3. In when(mock.find(1)).thenReturn(x), what does when receive as its argument?

    when only receives the result of the setup call. It finds the real call in thread-local state recorded by the interceptor.
  4. 4. If two stubbings match the same call, which one answers?

    Stubbings are searched newest first, so a later, more specific stub overrides an earlier general one.

Summary

  • A mock is a generated object whose methods all go through one interceptor.
  • The interceptor records the call, finds a matching stubbing (newest first) or falls back to the default answer.
  • when(mock.call()) works through a per-thread "last call" slot; the argument itself is ignored.
  • Mockito uses Byte Buddy for class generation and Objenesis to skip constructors.
  • The stand-in library on this site rebuilds the same skeleton on top of java.lang.reflect.Proxy, for interfaces only.

Next: Mockito with JUnit and Annotations