Code Smell 203 - Irrelevant Test Information

Irrelevant data distract the reader's attention

TL;DR: Don't add unnecessary information to your assertions

Problems

  • Readability

  • Maintainability

Solutions

  1. Remove irrelevant data

  2. Leave only the needed assertions

Context

Tests should be minimal and follow the SetUp/Exercise/Assert pattern

Sample Code

Wrong

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 the 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"

Right

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"

Detection

[X] Semi-Automatic

We can find some patterns in not needed assertions.

Tags

  • Testing

Conclusion

Tests should be prose. Always focus on the reader. It might be you a couple of months from now.

Relations

More Info

Disclaimer

Code Smells are my opinion.

Credits

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


This article is part of the CodeSmell Series.