Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Notification Dispatcher

Test a dispatcher that tries channels in order, falls back on failure, respects quiet hours with an injected Clock, and never contacts a channel it should skip.

Notification code is a great practice target for mocking: several outgoing channels, fallback rules, time-dependent behavior and plenty of "must not call" requirements. In this project you build a dispatcher that sends a message through the channels a user prefers, in order, until one works. During quiet hours it only uses the quietest channel (email).

You will practice four skills from this course: stubbing different answers per channel, verifying call order and absence, injecting a Clock for time, and throwing exceptions from a collaborator. Mockito is not available on this site, so the runnable test suite uses the labelled Mini stand-in; the real Mockito version is shown after it.

Specification

  • A Channel has a name() and boolean send(String user, String text). It returns false when the delivery fails and may also throw.
  • Dispatcher.notify(user, text) takes the user's preferred channel names (from Preferences) and tries them in order.
  • It stops at the first channel that returns true and reports DELIVERED_BY:<name>.
  • A channel that returns false or throws is skipped, and the next one is tried.
  • If every channel fails: FAILED.
  • Quiet hours are 22:00 to 07:00 UTC. In quiet hours only the email channel may be used; other channels are not even contacted. If email is not in the user's list: DEFERRED.
flowchart TD
  S["notify(user, text)"] --> Q{"Quiet hours?"}
  Q -->|"Yes"| E{"email preferred?"}
  E -->|"Yes"| T1["try email only"]
  E -->|"No"| D["DEFERRED"]
  Q -->|"No"| T2["try preferred channels in order"]
  T1 --> R["DELIVERED_BY or FAILED"]
  T2 --> R

The clock decides which list of channels the dispatcher may use.

Code and tests

Channels are looked up by name from a map, so the tests can mock each one. Study how every test stubs only the channels it should reach and verifies that the others were not touched.

Java Dispatcher and its test suite

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.

A few details worth noticing:

  • All channels are separate mocks of one interface. Their names matter for readability; in real Mockito use @Mock Channel email; and so on, or mock(Channel.class, "email") to put the name in error messages.
  • The test for "all channels failing" needs no stubs: unstubbed boolean methods return false, which is exactly the failure the test describes. That is a legitimate use of the default answer, though a short comment in the test helps readers.
  • The clock is a plain argument. No static mocking, no sleeping, no dependence on when the tests run.

Real Mockito version of two tests

Java
@ExtendWith(MockitoExtension.class)
class DispatcherTest {

    @Mock(name = "email") Channel email;
    @Mock(name = "sms") Channel sms;
    @Mock(name = "push") Channel push;
    @Mock Preferences prefs;

    private Dispatcher dispatcherAt(String utcTime) {
        Clock clock = Clock.fixed(Instant.parse("2030-03-01T" + utcTime + "Z"), ZoneOffset.UTC);
        return new Dispatcher(Map.of("email", email, "sms", sms, "push", push), prefs, clock);
    }

    @Test
    void exceptionFallsThroughToNextChannel() {
        when(prefs.channelsFor("ana")).thenReturn(List.of("push", "email"));
        when(push.send("ana", "hi")).thenThrow(new IllegalStateException("down"));
        when(email.send("ana", "hi")).thenReturn(true);

        assertEquals("DELIVERED_BY:email", dispatcherAt("12:00:00").notify("ana", "hi"));
    }

    @Test
    void quietHoursNeverContactPushOrSms() {
        when(prefs.channelsFor("ana")).thenReturn(List.of("push", "sms", "email"));
        when(email.send("ana", "hi")).thenReturn(true);

        dispatcherAt("23:30:00").notify("ana", "hi");

        verifyNoInteractions(push, sms);
    }
}

Using verifyNoInteractions(push, sms) is the one-line form of the two negative verifications from the stand-in. With strict stubs, the prefs.channelsFor stubs here are all used, so the tests pass the strictness check.

Exercises

  1. Add a rule: if a channel throws, the dispatcher must log the exception through a Logger collaborator. Verify the log call with an ArgumentCaptor for the message.
  2. Add retries: a channel may be tried twice before moving on. Stub it to fail once and then succeed (consecutive answers) and verify exactly two calls.
  3. Make quiet hours configurable and test the boundaries 21:59:59, 22:00:00, 06:59:59 and 07:00:00.
  4. Use InOrder to prove that channels are tried in preference order.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Why does the dispatcher take a Clock instead of calling LocalTime.now()?

    An injected Clock is the standard seam for time; Clock.fixed makes tests repeatable at any hour.
  2. 2. Which verification best expresses 'during quiet hours push and sms must never be contacted'?

    verifyNoInteractions fails if the mocks were touched in any way.
  3. 3. A test expects FAILED and stubs nothing on the three channels. What do their send methods return?

    Mockito mocks return false for boolean methods unless stubbed, so every channel looks like a failure.

Summary

  • Model each channel as a separate mock and stub only the channels a scenario should reach.
  • Use verifyNoInteractions or verify(..., never()) for "must not be contacted" rules.
  • Inject a Clock for time-dependent rules and test the boundary values.
  • Exceptions from collaborators are an input like any other: stub with thenThrow and assert the fallback.
  • Defaults (false) can be a legitimate scenario, but name it in the test.

Next: Project: payment retry with backoff