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

Avoiding Logic in Tests

Keep tests simple and linear by eliminating conditionals, loops, and complex calculations that obscure intent.

Avoiding Logic in Tests

You'll learn why tests should be simple, linear scripts without conditionals, loops, or complex calculations.

The Core Idea

Tests exist to verify your production code works correctly. When you add logic to your tests—if statements, loops, switch cases, or complex calculations—you've introduced code that itself needs testing. This defeats the purpose: who tests the tests?

A good test reads like a straightforward recipe: arrange your ingredients, perform one action, check the result. When you add conditionals like if (result.isValid()) or loops like for (item in items), you're asking the reader to mentally execute that logic to understand what's being verified. This obscures the test's intent and creates opportunities for bugs in your test code.

Why It Matters

Logic in tests creates maintenance nightmares. A test with an if-statement might pass even when it shouldn't, because the condition chose the wrong path. A test with a loop might accidentally pass with zero iterations. Complex calculations in assertions mean you're duplicating production logic—and if that logic is wrong, both test and code will be wrong in the same way.

Think of tests as courtroom evidence: you want clear, unambiguous facts ("the function returned 42"), not conditional statements ("if the defendant is guilty, then..."). The simpler your tests, the more confident you can be in their verdict.

The Alternative

When you're tempted to add logic, usually you need multiple separate tests instead. Each test covers one specific scenario with its own clear arrange-act-assert flow. Extract complex setup into helper methods with clear names, but keep the test body itself brutally simple.

Key Takeaway: Tests should be the dumbest, most obvious code in your codebase—eliminate conditionals, loops, and complex logic so tests remain trustworthy and easy to understand.