Read Code Fast
Lesson 23 Hollow tests
asserting on mocks, blind snapshots, skipped tests, tests rewritten to pass
What you'll learn
- Spot tests that can never fail: mocks, skips and always-true assertions
- Prove a test is hollow by breaking the code on purpose
- Refuse a test that was rewritten to match a bug
The AI says "I added tests and they all pass." Green only means nothing failed. It does not mean anything was checked.
The idea
A test is only worth something if it can fail. Ask one question of every test: if the code were wrong, would this go red? Hollow tests answer no. The usual kinds: a test that asserts on a mock (a fake it set up itself), an assertion that can never fail (or True), a skipped test, a blind expected value copied from whatever the code returned, and a failing test the AI rewrote to pass.
The proof is quick: break the code on purpose and run the tests. If they stay green, they are decoration. In the snippet the function total_with_tax forgets to add the tax, and pytest still says green.
1from unittest.mock import MagicMock2import pytest3from cart import total_with_tax45def test_adds_20_percent_tax():6 calc = MagicMock(return_value=120)7 assert calc(100) == 12089@pytest.mark.skip(reason="flaky")10def test_rounds_to_whole_cents():11 assert total_with_tax(10.1) == 12.121213def test_never_goes_negative():14 assert total_with_tax(-5) >= 0 or True1516def test_total_for_100():17 assert total_with_tax(100) == 100
- Line 6 A mock of the very function under test. The assertion checks the fake the test just built, so
total_with_taxnever runs. - Line 9 Skipped. It never runs, so it can't fail. Ask why it was skipped, and who turns it back on.
- Line 14
or Truemakes the condition true whatever the total is. This line can never fail. - Line 17 Where did this 100 come from? If it was copied from the first run, it records whatever the code returned, bug included.
Take away
- Green means nothing failed, not that something was checked.
- Ask of every test: if the code were wrong, would this go red?
- Break the code on purpose. A test that stays green is decoration.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.