Test doubles without Mockito

Code that reads the clock is hard to test, because the real clock moves. The usual fix is a dependency: the service asks an interface for the hour, and a test passes an object that answers a fixed hour. That object is a test double, and it needs no library. This lesson writes a fake by hand and uses it in two tests.

A dependency and a double

A fake is a working implementation with a shortcut: a map instead of a database, a fixed hour instead of the system clock. A stub answers with a value and does nothing else. A mock also records the calls so the test can assert on them. All three are test doubles, and a hand-written class can be any of them.

The clock interface

Clock.java is one method: the hour of the day. The production implementation would call LocalTime.now(); the test implementation returns the number it was built with.

interface Clock { int hour(); }

The service under test

Service.java takes a Clock in its constructor and chooses a greeting from the hour. The dependency is the seam: the test replaces it without touching the service.

public class Service { private final Clock clock; Service(Clock clock) { this.clock = clock; } String greeting() { if (clock.hour() < 12) { return "good morning"; } return "good evening"; } }

A fake in the test class

The fake is a small class inside the test. It implements Clock, stores the hour and returns it. Two tests pass 9 and 20 and read the two greetings; the real clock is never called, so the tests pass at any time of day.

import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class ServiceTest { static class FixedClock implements Clock { private final int hour; FixedClock(int hour) { this.hour = hour; } @Override public int hour() { return hour; } } @Test void greetsInTheMorning() { assertEquals("good morning", new Service(new FixedClock(9)).greeting()); } @Test void greetsInTheEvening() { assertEquals("good evening", new Service(new FixedClock(20)).greeting()); } }

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Clock.java Service.java ServiceTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ ServiceTest ✔
│     ├─ greetsInTheEvening() ✔
│     └─ greetsInTheMorning() ✔
└─ JUnit Vintage ✔

Test run finished after 338 ms
[         4 containers found      ]
[         0 containers skipped    ]
[         4 containers started    ]
[         0 containers aborted    ]
[         4 containers successful ]
[         0 containers failed     ]
[         2 tests found           ]
[         0 tests skipped         ]
[         2 tests started         ]
[         0 tests aborted         ]
[         2 tests successful      ]
[         0 tests failed          ]

Mockito is not in this image

A library such as Mockito builds the fake for you and records the calls. It is not in this image, and there is no network to download it, so this course does not run a Mockito test. The snippet below is the shape such a test would have; it is shown as an annotation and a call, not as a program, and it was not compiled here:

Clock clock = mock(Clock.class); when(clock.hour()).thenReturn(9); assertEquals("good morning", new Service(clock).greeting()); verify(clock).hour();

The hand-written fake in this lesson does the first two lines without a library: it returns 9 and it is the only clock the service sees. A fake that records calls is a few lines more, and it keeps the test readable with no mocking framework to learn.

Exercises

  1. Add a fake that returns 12 exactly and decide which greeting the boundary should produce.
  2. Turn FixedClock into a recording fake: keep a count of hour() calls and assert it in the test.
  3. Give the service a second dependency and a second fake. How many constructor arguments does the test pass now?
  4. Write a production SystemClock that calls LocalTime.now() and explain why the service tests do not use it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a fake?

    Answer

    A working implementation with a shortcut for the test

    A fake implements the interface with a simple stand-in, such as a fixed hour.

  2. Why does the service take the clock in its constructor?

    Answer

    The dependency is a seam the test can replace

    Injection lets the test pass a fake without changing the service.

  3. Why is Mockito not used on this page?

    Answer

    It is not in the image and there is no network to download it

    The course runs only what the image has, and Mockito is absent.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println(Math.min(9, 12)); } }

    Answer

    9

    Nine is less than twelve, so the comparison is true.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(Math.max(20, 12)); } }

    Answer

    20

    Twenty is not less than twelve, so the comparison is false.

  6. What does this program print? public class Q3 { public static void main(String[] args) { String greeting = "good morning"; System.out.println(greeting.length()); } }

    Answer

    12

    The phrase has twelve characters, the space included.

  7. What does this program print? public class Q4 { public static void main(String[] args) { int hour = 9; hour = hour + 11; System.out.println(hour); } }

    Answer

    20

    The assignment adds 11 to 9 and stores 20.

  8. What is the difference between a stub and a mock?

    Answer

    A stub answers with a value; a mock also records calls for assertions

    A mock adds verification of the calls to the answers a stub gives.

  9. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println("evening".startsWith("even")); } }

    Answer

    true

    The word begins with even, so startsWith is true.

  10. Which test is flaky if the service reads the real clock?

    Answer

    The one that expects a morning greeting near midnight

    A real clock changes with the hour, so a greeting test can pass in the morning and fail at night.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev