Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Practice: Mockito Exercises

Eight hands-on Mockito exercises on spies, partial mocks, static and time seams, strict stubs and test design, with runnable stand-in solutions and real Mockito answers.

You have now seen spies, partial mocks, static and final mocking, strictness, extensions and the patterns that keep mock-heavy tests healthy. This final lesson gives you eight exercises to cement them. Each has a task, a hint and a solution. Try the task on paper or in your own project first; then compare.

Mockito does not run on this site. The first three solutions are runnable with the labelled Mini stand-in so you can experiment in the browser. The others are real Mockito code to read and to copy into your own IDE.

How to practice

  1. Read the task and write the test before looking at the solution.
  2. Predict what will fail and why.
  3. Change the code under test and see whether your test notices (a good test fails when the behavior breaks).

Exercise 1: spy a calculator without side effects

Task. ReportPrinter.print() writes to disk and then returns the number of lines. Test the line counting of ReportBuilder (a real class that calls print() internally) without touching the disk.

Hint. A spy keeps the real logic; stub the one method with the side effect, with the do family.

Java
ReportBuilder spy = spy(new ReportBuilder(lines));
doNothing().when(spy).writeToDisk();       // void method with a side effect
assertEquals(3, spy.build());
verify(spy).writeToDisk();

Exercise 2: partial mock of an abstract class

Task. abstract class Greeting { String render() { return prefix() + name() + "!"; } String prefix() { return "Hello, "; } abstract String name(); }. Test render() without writing a subclass.

Hint. mock(Greeting.class, CALLS_REAL_METHODS) and stub the abstract method.

Java
Greeting greeting = mock(Greeting.class, CALLS_REAL_METHODS);
doReturn("Ana").when(greeting).name();
assertEquals("Hello, Ana!", greeting.render());

Exercise 3: make time and randomness injectable (runnable)

Task. A DiscountCodes class should produce a code like SALE-2030-03-01-X7Q from the current date and a random suffix. Make the test deterministic without static mocking.

Hint. Inject a Clock and a Supplier<String> for the suffix.

Java Solution: Clock plus Supplier seams

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.

Exercise 4: find the unnecessary stub (runnable)

Task. The test below contains a stub the code never reaches. Find it with strictness, then decide whether to delete it or fix the input.

Java Which stub is dead? Use the strict check

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.

Answer. The test asks for 5 pens while only 2 are in stock, so the code returns SOLD OUT before it reads the price. The prices.cents stub is dead. Either delete it (the test is about the sold-out path) or ask for 2 pens to test the total. Real Mockito's STRICT_STUBS reports this as UnnecessaryStubbingException (see Strict stubs and unnecessary stubbing).

Exercise 5: static mock with a clean scope

Task. Legacy code calls FeatureFlags.isEnabled("new-checkout") (static). Test both branches without changing the production code.

Java
@Test
void usesNewCheckoutWhenEnabled() {
    try (MockedStatic<FeatureFlags> flags = mockStatic(FeatureFlags.class)) {
        flags.when(() -> FeatureFlags.isEnabled("new-checkout")).thenReturn(true);

        assertEquals("v2", new CheckoutRouter().route());

        flags.verify(() -> FeatureFlags.isEnabled("new-checkout"));
    }
}

Follow-up. Refactor CheckoutRouter to receive a Predicate<String> flags and rewrite the test with a lambda. Which one is shorter? Which one survives changing the flag library?

Exercise 6: capture and inspect

Task. AuditService.log(User, Action) builds an AuditEvent and calls sink.publish(event). Verify that the event contains the user name and the action without writing equals on AuditEvent.

Java
ArgumentCaptor<AuditEvent> captor = ArgumentCaptor.forClass(AuditEvent.class);
service.log(new User("ana"), Action.DELETE);

verify(sink).publish(captor.capture());
AuditEvent event = captor.getValue();
assertEquals("ana", event.user());
assertEquals(Action.DELETE, event.action());

Exercise 7: remove a deep stub

Task. when(order.getCustomer().getAddress().getCountry().getVatRate()).thenReturn(0.19) uses RETURNS_DEEP_STUBS. Refactor the code so the test needs one stub on a neighbor.

Answer sketch. Add Order.vatRate() that hides the chain, depend on that single method (or on a VatPolicy interface), and build the domain objects for real in other tests. See Deep stubs and the Law of Demeter.

Exercise 8: review and repair a bad test

Task. Review this test and list at least five problems:

Java
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class UserServiceTest {

    @Mock User user;
    @Mock Address address;
    @Spy UserService service = new UserService(null);

    @Test
    void test1() {
        when(user.getAddress()).thenReturn(address);
        when(address.getCity()).thenReturn("Berlin");
        when(address.getZip()).thenReturn("10115");
        doReturn("x").when(service).helper();

        service.process(user);

        verify(service).helper();
        verify(user).getAddress();
        verify(address).getCity();
        verifyNoMoreInteractions(user, address);
    }
}

Problems to find: the class is lenient so the unused getZip stub is hidden; User and Address look like value objects and should be real; the service under test is a spy and a method of it is stubbed; its dependency is null; the test name says nothing; the assertions are only interaction checks and there is no outcome assertion; and verifyNoMoreInteractions freezes the implementation. The repaired version builds a real User with a real Address, constructs the service with its real collaborators or fakes, and asserts on the result of process.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which approach is generally better for legacy static calls to a feature-flag class you own?

    Injection needs no instrumentation or thread scoping; mockStatic is the fallback for code you cannot change yet.
  2. 2. A test uses ArgumentCaptor on publish(event). What is the benefit?

    Captors give access to the exact object passed so you can assert field by field.
  3. 3. You find that one stub in a test is never reached. What is the best first question?

    An unused stub signals either a dead line or a test that does not reach the intended code. Investigate before silencing.

Summary

  • Spies keep real logic and stub side effects with the do family; partial mocks with CALLS_REAL_METHODS test abstract templates.
  • Prefer seams (Clock, Supplier, injected predicates) to static mocking; keep mockStatic scoped and closed.
  • Strict stubs find dead stubs; fix the test rather than silencing it.
  • Captors, real value objects and result assertions make tests that survive refactoring.
  • Review your own tests for smells regularly.

Next: back to the Mockito track overview