Unit testing OO code
medium 50 minA 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
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
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
| Does | For | Example | |
|---|---|---|---|
| dummy | nothing | fills a parameter | unused 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
majorThe test repeats the code and breaks with every refactoring.
Wronginv.available.assert_called_once()inv.reserve.assert_called_once()Rightassert inventory.stock["mug"] == 3Create inside the method
criticalNo place to hand in a stand-in.
Wrongdef process(self, o): Stripe("key").charge(o)Rightdef __init__(self, payment): self._payment = paymentSleep as a test tool
majorSlow, and wrong on a slow machine.
Wrongtime.sleep(60)assert guard.allowed("noor")Rightclock.advance(60)assert guard.allowed("noor")A fake that accepts everything
criticalTests pass that could not pass in production.
Wrongdef reserve(self, p, q): self.stock[p] -= qRightif not self.available(p, q): raise ValueError("not enough")Loose mocks
majorA typing error in a method name is accepted.
Wrongrepo = Mock()Rightrepo = 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