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

One Assertion Per Test vs Multiple Assertions

Trade-offs between single-assertion tests and tests with multiple related assertions for the same behavior.

One Assertion Per Test vs Multiple Assertions

You'll learn: When to use a single assertion per test versus grouping multiple assertions together, and the trade-offs involved.

The Core Question

After you Act (execute the behavior), how many checks should you make in the Assert phase? Should each test verify exactly one thing with one assertion, or can you group related assertions together?

The Single-Assertion Perspective

Some developers advocate for one assertion per test. The reasoning: when a test fails, you know exactly what broke. If a test named testUserEmailIsValidated contains only assert(user.email).isValid(), failure pinpoints the problem immediately. This approach makes tests extremely focused and failure messages crystal-clear.

The Multiple-Assertions Reality

However, strict one-assertion-per-test can be impractical. Imagine testing that a createUser function properly initializes a user object. You'd reasonably want to verify:

assert(user.name).equals("Alice")
assert(user.email).equals("alice@example.com")
assert(user.isActive).isTrue()

These assertions test one behavior (user creation), just from multiple angles. Splitting into three separate tests would mean duplicating setup three times and obscuring that you're verifying a single concept.

The Practical Balance

Test one behavior, not necessarily one assertion. If multiple assertions verify different facets of the same outcome—like checking an object's multiple properties after one action—keep them together. But if assertions verify unrelated behaviors, split them into separate tests.

Think of it like checking a package delivery: confirming the box arrived, contains the right item, and isn't damaged are all part of verifying "successful delivery," not three separate concerns.

Key Takeaway: Prefer one assertion per test for clarity, but group multiple assertions when they collectively verify a single, cohesive behavior—prioritize test readability and avoiding duplication over rigid rules.