Lesson 2 · Unit 02
Test doubles
Stubs, spies, fakes and mocks stand in for the slow parts
What you practise
- Stubs, fakes, mocks and spies
- Replacing a network call or a clock
- The cost of mocking too much
- Testing behaviour, not implementation
Try a question from this lesson
Pick one
In production the balance lookup calls a bank over the network. What should a test pass as the third argument?
def can_buy(uid, price, get_balance):
return get_balance(uid) >= pricefunction canBuy(uid, price, getBalance) {
return getBalance(uid) >= price;
}function canBuy(
uid: number,
price: number,
getBalance: (uid: number) => number,
): boolean {
return getBalance(uid) >= price;
}Correct answer
A tiny function that returns a fixed balance
Why
The function only needs something it can call for a balance. A stand-in that always answers 80 makes the test fast, free and repeatable, and tests the one thing this function decides: the comparison.
TypeScript note(uid: number) => number is a function type: anything callable with a number that returns a number fits, whether it is the real lookup or a stand-in.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Stand-ins
A test double stands in for something slow, flaky or dangerous: a network, a clock, a mail server.
A stub returns canned answers. A spy also records how it was called. A fake is a small working version, like a dictionary in place of a database. A mock fails the test by itself when the calls are not the ones it expects.
10 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.