AlgoViz

Chain of responsibility

medium 45 min

A request travels past several handlers until one takes it, or until one stops it.

Watch lesson4:36

Verify

Trace, boundaries, and tests that find real bugs.

The point: test each handler alone, then the order, then the end.

Trace

Ticket 4 by hand

StepObjectcanHandleStack
1Level1CRITICAL is LOW? noLevel1
2Level2CRITICAL is MEDIUM? noLevel1, Level2
3EngineeringCRITICAL is HIGH or more? yesLevel1, Level2, Engineering
4Engineeringpager gets 4, text returnedLevel1, Level2
5Level2, Level1return what they gotempty

Tests

Three kinds

Python
class Handler:    def __init__(self): self.next = None    def handle(self, n):        if self.can(n): return self.name        if self.next is None: raise LookupError(n)        return self.next.handle(n)class Low(Handler):    name = "low"    def can(self, n): return n < 10class High(Handler):    name = "high"    def can(self, n): return 10 <= n < 100class Spy(Handler):    name = "spy"    def __init__(self): super().__init__(); self.seen = []    def can(self, n): self.seen.append(n); return Truedef link(*hs):    for a, b in zip(hs, hs[1:]): a.next = b    return hs[0]# 1. alone: the boundary of one ruleassert Low().can(9) and not Low().can(10)# 2. passing on: the spy sees exactly what Low did not takespy = Spy()chain = link(Low(), spy)assert chain.handle(5) == "low" and spy.seen == []assert chain.handle(50) == "spy" and spy.seen == [50]# 3. the endtry:    link(Low(), High()).handle(1000)    raise AssertionError("lost")except LookupError as e:    print("end reached with", e)# 4. order does not matter, because the rules exclude each otherfor n in (0, 9, 10, 99):    assert link(Low(), High()).handle(n) == link(High(), Low()).handle(n)print("all ok")
Run it. The spy is a real handler that records, so nothing depends on a mocking library.
Edit and run it in your browser
Java
@Testvoid level1PassesACriticalTicketOn() {    List<Ticket> seen = new ArrayList<>();    SupportHandler recorder = new SupportHandler() {        protected boolean canHandle(Ticket t) { return true; }        protected String resolve(Ticket t) { seen.add(t); return "recorded"; }    };    Ticket crash = new Ticket(1, "Crash", Priority.CRITICAL);    String answer = Chain.link(new Level1(), recorder).handle(crash);    assertEquals("recorded", answer);     // the answer came back    assertEquals(List.of(crash), seen);   // and the request arrived}
The same in JUnit. A recording handler instead of verify(h2): Mockito can only verify calls on a mock or a spy, and a real Level2 is neither.

What each test catches

BugFound by
Forgot return before next.handleasserting the answer, not only the call
Off by one at a limitthe boundary test of one handler
Two rules overlapthe order test: swapping changes the result
A gap between rulesevery value of the enum through the real chain
Chain starts at the wrong handlersending a request the first one must refuse