AlgoViz

Unit testing OO code

medium 50 min

A unit test runs one class alone, with stand-ins for the things it talks to, and checks what it promises.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:09

See it run

One real object, stand-ins around it, and what the test looks at.

Operations

Swap the world

The same service with real collaborators and with doubles.

Step 1 of 4

Real collaborators

testOrderServiceTestserviceOrderServiceunder testyesinventoryPostgresneedsa serverpaymentStripe clientneedsreal moneymailerSMTPneedsa network

A test would need a server, money and a network.

Step 1: Real collaborators

class OrderService:    def __init__(self, payment, inventory, mailer):        self._payment = payment        self._inventory = inventory        self._mailer = mailer# production: OrderService(Stripe(), Postgres(), Smtp())# test:       OrderService(StubPayment(), FakeInventory(), SpyMailer())
Good for
Every class that talks to others
Costs
Small interfaces

Replace what is slow, random or expensive. Keep the rest real.

In the real world

The same unit testing oo code doing real jobs. Pick one and step through it.

What each is for.

Step 1 of 5

Dummy

DoesForExample
dummynothingfills a parameterunused logger
stub
fake
spy
mock

Only fills a place.

Step 1: Dummy

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Verify every call

    major

    The test repeats the code and breaks with every refactoring.

    Wrong
    inv.available.assert_called_once()inv.reserve.assert_called_once()
    Right
    assert inventory.stock["mug"] == 3
  • Create inside the method

    critical

    No place to hand in a stand-in.

    Wrong
    def process(self, o):    Stripe("key").charge(o)
    Right
    def __init__(self, payment):    self._payment = payment
  • Sleep as a test tool

    major

    Slow, and wrong on a slow machine.

    Wrong
    time.sleep(60)assert guard.allowed("noor")
    Right
    clock.advance(60)assert guard.allowed("noor")
  • A fake that accepts everything

    critical

    Tests pass that could not pass in production.

    Wrong
    def reserve(self, p, q):    self.stock[p] -= q
    Right
    if not self.available(p, q):    raise ValueError("not enough")
  • Loose mocks

    major

    A typing error in a method name is accepted.

    Wrong
    repo = Mock()
    Right
    repo = create_autospec(Repo, instance=True)

Interview tips

  • Design first

    • Collaborators come in
    • Small ports
    • Return results
  • Name tests aloud

    • Main path
    • Each refusal
    • The boundary
  • Choose doubles

    • Real if cheap
    • Fake for state
    • Spy for what leaves
  • Show doubt

    • What can the fake hide?
    • What if reserve fails after charge?
    • Break it once