Irrelevant data distract the reader's attention
TL;DR: Don't add unnecessary information to your assertions
-
Readability
-
Maintainability
-
Remove irrelevant data
-
Leave only the needed assertions
Tests should be minimal and follow the SetUp/Exercise/Assert pattern
def test_formula_1_race():
# Setup
racers = [
{"name": "Lewis Hamilton",
"team": "Mercedes",
"starting_position": 1,
"car_color": "Silver",
"car_model": "W12"},
{"name": "Max Verstappen",
"team": "Red Bull",
"starting_position": 2,
"car_color": "Red Bull",
"car_model": "RB16B"},
{"name": "Sergio Perez",
"team": "Red Bull",
"starting_position": 3,
"car_color": "Red Bull",
"car_model": "RB16B"},
{"name": "Lando Norris",
"team": "McLaren", "starting_position": 4,
"car_color": "Papaya Orange",
"car_model": "MCL35M"},
{"name": "Valtteri Bottas",
"team": "Mercedes",
"starting_position": 5,
"car_color": "Silver",
"car_model": "W12"},
]
# Exercise
winner = simulate_formula_1_race(racers)
# Test
assert winner == "Lewis Hamilton"
# This is all irrelevant to winner asserting
assert racers[0]["car_color"] == "Silver"
assert racers[1]["car_color"] == "Red Bull"
assert racers[2]["car_color"] == "Red Bull"
assert racers[3]["car_color"] == "Papaya Orange"
assert racers[4]["car_color"] == "Silver"
assert racers[0]["car_model"] == "W12"
assert racers[1]["car_model"] == "RB16B"
assert racers[2]["car_model"] == "RB16B"
assert racers[3]["car_model"] == "MCL35M"
assert racers[4]["car_model"] == "W12"
def test_formula_1_race():
# Setup
racers = [
{"name": "Lewis Hamilton", "starting_position": 1},
{"name": "Max Verstappen", "starting_position": 2},
{"name": "Sergio Perez", "starting_position": 3},
{"name": "Lando Norris", "starting_position": 4},
{"name": "Valtteri Bottas" "starting_position": 5},
]
# Exercise
winner = simulate_formula_1_race(racers)
# Test
assert winner == "Lewis Hamilton"
[X] Semi-Automatic
We can find some patterns in not needed assertions.
- Testing
Tests should be prose. Always focus on the reader. It might be you a couple of months from now.
Code Smell 76 - Generic Assertions
xUnit Test Patterns: Refactoring Test Code
Code Smells are my opinion.
Photo by Evan Demicoli on Unsplash
Take reasonable steps to test, document, and otherwise draw attention to the assumptions made in every module and routine.
Daniel Read
Software Engineering Great Quotes
This article is part of the CodeSmell Series.