Testing legacy code
Putting tests on code that has none before changing it: characterization test, seams, breaking dependencies, sprout method, after Feathers.
- 23 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Legacy code: what is it?
Show the answer
Code without tests, which one hesitates to change for fear of breaking what works. For Feathers age hardly matters: the absence of tests defines it.
A function written yesterday without tests is already legacy code: without a net, every change is a bet.
For this legacy code, which expected value must a characterization test of
remise(0)pin down?
```python
def remise(montant):
if montant > 100:
return montant // 10
if montant > 0:
return 5
return -1`-105None
Show the answer
-1remise(0)really returns -1, probably unexpected: that is the value to pin down. 'Fixing' it to 0 in the test changes behaviour instead of describing it. It can be fixed afterwards, knowingly.A characterization test checks what the code …, not what it ….
Show the answer
A characterization test checks what the code actually does, not what it should do.
The aim is not to prove the code is correct, but to know at once whether a change altered its behaviour.
Characterization test: what is it?
Show the answer
A test that pins down what the code really does today, oddities included, to detect any unintended change in its behaviour.
One writes the call, reads the returned value, then copies it as the expected value. The test does not say the code is right, only that it has not moved.
A shipping-cost calculation must be added to a 200-line method with no tests, which cannot be tested yet. Which approach limits the risk?
- Write the calculation in a separately tested sprout method, called with one line
- Insert the calculation in the right place of the method, then test the whole by hand
- First rewrite the whole method cleanly, then add the calculation
- Postpone the addition until the whole method is covered by tests
Show the answer
Write the calculation in a separately tested sprout method, called with one line
The sprout method gives new code with its tests without touching the old code, which stays intact. Rewriting first without a net is the bet the approach tries to avoid.