Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Patterns and Pitfalls

Deep Stubs and the Law of Demeter

Understand Mockito's RETURNS_DEEP_STUBS for chained calls, why a test that needs it signals a Law of Demeter violation, and how to refactor so ordinary stubs are enough.

Some code reads like a train: order.getCustomer().getAddress().getCountry().getVatRate(). To test it with plain mocks you need four mocks and three stubs that return the next mock. Mockito offers a shortcut, RETURNS_DEEP_STUBS, which creates the intermediate mocks for you. It works, but a test that needs it usually points at a design problem called a Law of Demeter violation. This lesson shows the feature, the problem, and the refactoring that makes the test (and the code) simpler.

Mockito does not run on this site. Real code is read-only; the runnable examples use the labelled Mini stand-in and plain Java.

The problem: long chains

Java
class TaxService {
    double vatFor(Order order) {
        return order.getCustomer().getAddress().getCountry().getVatRate();
    }
}

Plain Mockito test:

Java
Order order = mock(Order.class);
Customer customer = mock(Customer.class);
Address address = mock(Address.class);
Country country = mock(Country.class);

when(order.getCustomer()).thenReturn(customer);
when(customer.getAddress()).thenReturn(address);
when(address.getCountry()).thenReturn(country);
when(country.getVatRate()).thenReturn(0.19);

Four mocks to check one number.

Deep stubs

Java
Order order = mock(Order.class, RETURNS_DEEP_STUBS);

when(order.getCustomer().getAddress().getCountry().getVatRate()).thenReturn(0.19);

assertEquals(0.19, new TaxService().vatFor(order));

With RETURNS_DEEP_STUBS, every call that returns a non-final, mockable type returns a new mock (the same one on repeated calls), and you can stub the end of the chain directly. The test is short. Limits:

  • Intermediate return types must be mockable (not final with the old mock maker, not primitives or String).
  • Generic return types can fail to resolve in some cases (for example type variables of a generic class).
  • It cannot mock types such as String; the last call in the chain must return something you can stub.

How deep stubs work (stand-in)

The stand-in below gives a mock a default answer that returns another mock whenever the return type is an interface. That is the heart of deep stubs: a cache of child mocks so the same call returns the same child.

Java A default answer that returns mocks

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 test walks down the chain once to get the end object, stubs it, and the service gets 0.19 through three automatically created mocks.

Why it smells: the Law of Demeter

The Law of Demeter (principle of least knowledge) says an object should talk to its direct neighbors, not reach through them. TaxService knows that an order has a customer, which has an address, which has a country, which has a VAT rate. If any link changes, TaxService breaks. And your test must rebuild the entire chain.

Deep stubs make the test easy, so the pain goes away, while the coupling stays. A test that is painful to write is giving you design feedback; deep stubs mute it.

The refactoring

Ask the neighbor for what you need:

Java
class Order {
    double vatRate() { return customer.address().country().vatRate(); }
}

class TaxService {
    double vatFor(Order order) { return order.vatRate(); }
}

Or pass only the needed value:

Java
double gross(double net, double vatRate) { return net * (1 + vatRate); }

The test of TaxService now needs a stub of one method. The chain exists once, inside Order, where it can be tested with real objects.

Java After the refactoring: one stub, no chain

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.

Notice that the domain objects are real. They are records with no side effects, so there is no reason to mock them (see Over-mocking and test smells).

When deep stubs are acceptable

  • Third-party APIs you cannot change with long fluent chains, such as some HTTP client builders or ORM query APIs. A deep mock or RETURNS_SELF keeps the test short. Wrapping the API behind your own interface is still better.
  • Legacy code you are about to refactor. Use deep stubs to put a test around it first, then change the design and simplify the test.

In new code, treat RETURNS_DEEP_STUBS as a warning light: ask what a shorter chain would look like.

RETURNS_SELF for fluent builders

Builders return this. With plain mocks each call returns null and the chain breaks. RETURNS_SELF fixes exactly that:

Java
RequestBuilder builder = mock(RequestBuilder.class, RETURNS_SELF);
when(builder.build()).thenReturn(request);

client.send(builder);     // builder.url(...).header(...).build() works

It returns the same mock for methods whose return type is the mock's own type.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What does RETURNS_DEEP_STUBS do?

    Each call that returns a mockable type returns a new mock (cached per method), enabling when(a.b().c()).thenReturn(x).
  2. 2. What design problem does a need for deep stubs often reveal?

    Long chains couple the code to the entire object graph. Ask a neighbor for what you need instead.
  3. 3. Which refactoring simplifies the test most?

    Hiding the chain inside one object and depending on that single method means one stub is enough.

Summary

  • RETURNS_DEEP_STUBS auto-creates mocks along a call chain; RETURNS_SELF helps with fluent builders.
  • Needing deep stubs in new code usually signals a Law of Demeter violation.
  • Refactor: add a delegating method, pass the value, or keep domain objects real.
  • Accept deep stubs for third-party chains and for tests around legacy code.

Next: Fakes, stubs and mocks: choosing