Course contentsShow
← Software Engineering
Lesson 433 of 1,93313. Unit Testing in DepthFree lesson

Testing One Thing at a Time

Focus each test on a single behavior or outcome to make failures easy to diagnose and understand.

Testing One Thing at a Time

What you'll learn: How focusing each test on a single behavior makes debugging faster and tests more maintainable.

The Core Idea

When writing unit tests, each test should verify exactly one behavior or outcome. If a test checks multiple things at once, a failure leaves you guessing: which part broke? Testing one thing at a time makes failures pinpoint the exact problem immediately.

Think of it like a medical diagnostic test. If one blood test checked for twenty different conditions simultaneously and came back "abnormal," you'd have no idea what's wrong. But if twenty separate tests each check one thing, a failure tells you precisely what needs attention.

Why It Matters

Clarity: When test_user_creation_sets_correct_name fails, you know exactly what broke—the name wasn't set correctly.

Fast debugging: No hunting through multiple assertions or behaviors to find the culprit.

Better documentation: Each test name describes a single, specific behavior your code guarantees.

Easier maintenance: Changes to one behavior only affect its focused test, not a sprawling multi-purpose test.

Applying This Principle

After your Arrange and Act steps (from the AAA pattern), your Assert section should verify one logical outcome. If you're tempted to add a second assertion for a completely different behavior, create a separate test instead.

# Good: Each test verifies one behavior
def test_user_creation_sets_name():
    user = create_user("Alice")
    assert user.name == "Alice"

def test_user_creation_sets_active_status():
    user = create_user("Alice")
    assert user.is_active == True

This doesn't mean literally one assert statement—sometimes verifying one behavior requires checking multiple related properties—but avoid testing unrelated outcomes together.

Key Takeaway: One test, one behavior. When a test fails, you should instantly know what went wrong without reading the test code.