A service and its fake

A cache is a promise about calls: the first read goes to the store, the second does not. A test of that promise cannot use the real store, because the real store is slow and does not say how often it was called. A fake that counts its calls can say it, and the test asserts on the count.

The slow store

ReportStore.java is one method. A real implementation would read a file or a database; the interface is all the service knows.

interface ReportStore { String load(String name); }

The service and its cache

ReportService.java keeps a map. The first call for a name goes through computeIfAbsent and calls the store; the second finds the value in the map and never calls it.

import java.util.HashMap; import java.util.Map; public class ReportService { private final ReportStore store; private final Map<String, String> cache = new HashMap<>(); ReportService(ReportStore store) { this.store = store; } String report(String name) { return cache.computeIfAbsent(name, store::load); } }

A fake that counts

The fake implements the interface and increments a counter on every load. It returns a value that names the input, so the test can tell one report from another. The counter is public because the test reads it; it is a test-only class and has no other caller.

The tests

The first test calls the service twice for one name and expects one call to the store. The second calls two names and expects two calls. Together they pin the cache down without touching a file.

import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class ReportServiceTest { static class CountingStore implements ReportStore { int calls; @Override public String load(String name) { calls++; return "report " + name; } } @Test void loadsOnceAndCaches() { CountingStore store = new CountingStore(); ReportService service = new ReportService(store); assertEquals("report sales", service.report("sales")); assertEquals("report sales", service.report("sales")); assertEquals(1, store.calls); } @Test void loadsEachNameOnce() { CountingStore store = new CountingStore(); ReportService service = new ReportService(store); service.report("sales"); service.report("costs"); assertEquals(2, store.calls); } }

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out ReportStore.java ReportService.java ReportServiceTest.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 ✔
│  └─ ReportServiceTest ✔
│     ├─ loadsEachNameOnce() ✔
│     └─ loadsOnceAndCaches() ✔
└─ JUnit Vintage ✔

Test run finished after 472 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          ]

Why not the real store

A real store would read a file or a database, and the test would have to prepare it and clean it. It also would not count the calls, so the cache promise would be invisible. The fake is the dependency replaced at its seam, and the service does not know the difference.

Mockito would generate the counting class, and the test would call verify(store, times(1)).load("sales"). The image has no Mockito, so the fake is written by hand; it is six lines and the test is the same shape.

Exercises

  1. Add a test that reads two names twice and expects two calls.
  2. Remove the cache and run. Which test fails first, and what does the message say?
  3. Make the fake return a value that does not contain the name and update the tests.
  4. Add a second fake that returns null for one name and decide what the service should do.

Questions

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

  1. What does the counting fake prove?

    Answer

    How many times the service called the store

    The counter records the calls, and the test asserts the number the cache promises.

  2. Why does the test pass the fake instead of the real store?

    Answer

    The fake is fast, deterministic and records calls

    A test double removes the file or database and adds the observation the test needs.

  3. What does computeIfAbsent do here?

    Answer

    Calls the store only when the name is not already cached

    The mapping function runs only for a missing key, which is the cache rule.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println("report " + "sales"); } }

    Answer

    report sales

    The two strings are joined, and the space is part of the first one.

  5. What does this program print? public class Q2 { public static void main(String[] args) { int calls = 0; calls++; calls++; System.out.println(calls); } }

    Answer

    2

    Two increments take the counter to 2.

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

    Answer

    5

    The word costs has five letters.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println("sales".equals("sales")); } }

    Answer

    true

    The two strings have the same characters, so equals is true.

  8. What is the seam in this design?

    Answer

    The ReportStore interface passed to the service

    The interface is the point where the test replaces the real store with a fake.

  9. What does this program print? public class Q5 { public static void main(String[] args) { java.util.Map<String, String> cache = new java.util.HashMap<>(); cache.put("sales", "report sales"); System.out.println(cache.get("sales")); } }

    Answer

    report sales

    The key sales maps to the report sales string.

  10. How many lines does the hand-written fake take?

    Answer

    About six: the class, the counter, the method and the return

    A counting fake is a small class, which is why the missing library does not block the test.

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

Banner image