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

Unit testing OO code

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

A unit test is a small program that builds one object, does one thing with it and checks the outcome. It runs in milliseconds, needs no network, no database and no clock, and gives the same answer every time.

A class seldom lives alone. It talks to a database, a mail server, a payment company. In a test these are replaced by test doubles: simple objects with the same interface. The class under test is real, everything slow, random or expensive around it is not.

This is only possible if the class lets itself be fed. A class that creates its own database connection cannot be tested without a database. So testability is a design property, and the first reader of your design is the test.

Why it exists

Safety. You may change the inside of a class and know in a second whether its promises still hold.

Location. When an end-to-end run fails, anything may be guilty. When a unit test fails, the class under test is, or its test.

Cases that are hard to make for real. A refused card, an empty store, midnight on 29 February: with a stand-in each is one line.

A short history

  1. 1994

    Kent Beck describes a testing framework for Smalltalk, SUnit. Its shape, a class with test methods and a fixture, is still used.

  2. 1997

    Kent Beck and Erich Gamma write JUnit for Java. Many languages copy it.

  3. 2000

    Tim Mackinnon, Steve Freeman and Philip Craig present Endo-Testing: Unit Testing with Mock Objects at the XP2000 conference.

  4. 2004

    Michael Feathers publishes Working Effectively with Legacy Code, with seams and characterization tests.

  5. 2007

    Gerard Meszaros publishes xUnit Test Patterns, which sorts out the names dummy, stub, spy, mock and fake. Martin Fowler's Mocks Aren't Stubs, revised in the same year, makes them widely known.

Words to know

System under test
The object that the test checks. It is real.
Test double
Any stand-in for a real collaborator, like a stunt double in a film.
Dummy
Passed to fill a parameter, never used.
Stub
Gives prepared answers. It controls the input of the object under test.
Fake
A small working version, such as a repository in a dict.
Spy
Records calls. The test looks at the record afterwards.
Mock
Knows in advance which calls it expects, and fails the test if they differ.
Fixture
The objects and data a test starts with.
Seam
A place where behaviour can be replaced without editing the code there.
State and interaction testing
Check the result that remains, or check which calls were made.
Flaky test
Passes and fails without a change of code.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Feed. Collaborators come in through the constructor

Understand it

Start here

A puppet's arm on a stand

Asha builds string puppets. The arm of one does not lift. Is it the arm, the shoulder, the string or the cross above? On the whole puppet nobody can tell.

Asha tests an arm
?

Take one part, put it on a stand, pull once, look at the mark. Then one dance with everything.

The problem

A class that cannot be tested

Python
class OrderService:    def process(self, order):        db = PostgresInventory("prod-host")            # 1 creates it        if datetime.now().hour >= 22:                  # 2 reads the clock            return        stripe.charge(order.customer, order.cents)     # 3 global function        db.reserve(order.product)        smtplib.SMTP("mail").sendmail(...)             # 4 no result to look at
Four walls: it creates its own collaborators, reads the clock, calls a static function and returns nothing.

The bad shape: the class fetches what it needs

testsOrderServiceTest+ test()OrderService+ process(order)

1/3A test wants one class

It creates an OrderService and calls process.

usesdepends on

The good shape: collaborators come in

asksOrderService+ process(order): Result«interface»Inventory+ available(p, q)+ reserve(p, q)

1/4Ask for an interface

The service says what it needs: available and reserve. It does not say who. Payment and mail work the same way.

usesimplements

This is dependency injection by hand: three constructor arguments. See dependency inversion.

Shape

Arrange, act, assert

One test from top to bottom

Six principles

  • Behaviour, not implementation

    Check what comes out. If a refactoring without change of behaviour breaks the test, the test knew too much.

  • One behaviour per test

    Not one assert at any price. Three asserts about the same outcome are fine. Two outcomes are two tests.

  • Arrange, act, assert

    Three blocks with an empty line between them. One act.

  • Inject what you must control

    Network, database, clock, random numbers, threads.

  • Test the edges

    Nothing, one, the limit, one more than the limit, refused, empty text, null.

  • Fast and alone

    Milliseconds, any order, no shared state. Slow tests are run less often.

Stand-ins

Five kinds of test double

DoubleWhat it doesUse it toIn the order test
DummyNothingFill a parameterA logger that is never called
StubPrepared answersControl inputsPayment says declined
FakeWorks, simplyKeep state without the real thingInventory in a map
SpyRecords callsLook at them afterwardsMails that were sent
MockExpects callsFail at once on a wrong callCharge once with c1 and 9999
Mock libraries make all of them with one function and call everything a mock. The names still help: they say what the test checks.

Which stand-in?

Python
from unittest.mock import Mock, create_autospecclass Inventory:    def available(self, product, quantity): ...    def reserve(self, product, quantity): ...class Shop:    def __init__(self, inventory): self.inventory = inventory    def sell(self, product, n):        if not self.inventory.available(product, n): return "OUT_OF_STOCK"        self.inventory.reserve(product, n)        return "OK"inv = create_autospec(Inventory, instance=True)inv.available.return_value = Trueassert Shop(inv).sell("mug", 2) == "OK"inv.reserve.assert_called_once_with("mug", 2)loose = Mock()loose.resrve("mug")                 # typing error, no complainttry:    inv.resrve("mug")               # autospec complainsexcept AttributeError as e:    print("caught:", e)
The same test with a mock library. create_autospec refuses methods and parameters that the real class does not have; a plain Mock accepts every typing error.
Edit and run it in your browser

How do you test that an order is saved?

BreaksMock the repository and check save was called
How
repo.save.assert_called_once()
Limit
Passes when the wrong order is saved, fails when you rename save to save_all. It repeats the code and checks little.
Choose when
Seldom.
WorksCheck the saved argument
How
Capture the order and compare its fields.
Limit
Still tied to one method of the repository.
Choose when
A message goes out and nothing can be read back.
StrongFake repository, read it back
How
After process, repo.get(id) has the right state.
Limit
The fake must be kept honest.
Choose when
Anything that stores.

A test that helps

  • Its name is a sentence about behaviour
  • Fails for one reason
  • Survives a refactoring
  • Needs no other test before it
  • Shows the important values and hides the rest in a builder

A test that hurts

  • test1
  • Forty lines of mock setup
  • Checks the order of private steps
  • Sleeps for two seconds
  • Copies the formula from the code into the assert

Summary

The whole topic in one minute.

Feed a class its collaborators, replace the slow and random ones by doubles, and check one promise per test in three parts: arrange, act, assert.

Prefer real objects, then fakes, then stubs. Check interactions only where the call itself is the promise, such as one mail sent or no charge made.

Doubles can lie. Run one contract test against the double and the real thing, and keep a few larger tests for the wiring.

  • If a class is hard to test, it is hard to use. Change the design first.
  • Inject what you cannot control: network, storage, time, random numbers, threads.
  • Arrange, act, assert, and one behaviour per test.
  • Real object, then fake, then stub, then spy or mock.
  • State tests survive refactoring better than interaction tests.
  • Keep fakes honest with a contract test.

Sources