Combining State and Behavior Verification
You'll learn when and how to effectively use both state and behavior verification together in a single test.
The Core Idea
Sometimes testing only the final outcome (state verification) or only the interactions (behavior verification) isn't enough. In real-world scenarios, you often need both: verify that your code called the right collaborators in the right way and that it produced the correct result.
Think of it like checking both the recipe steps and the final dish. A chef might follow all the steps correctly but still burn the meal—or skip steps but get lucky with timing. Checking both gives you complete confidence.
When to Combine Both Styles
Combine state and behavior verification when:
- Critical interactions matter alongside outcomes: You need to ensure a payment was attempted (behavior) and the order status was updated (state)
- Side effects must occur with results: Logging must happen (behavior) while data transforms correctly (state)
- Order of operations matters: A notification was sent (behavior) after validation succeeded (state)
How to Do It Effectively
Keep your tests focused—don't verify everything. Verify:
- The most critical interaction(s) with test doubles (behavior)
- The final state or return value (state)
Example scenario (plain English):
When processing a refund:
- Verify the payment gateway was called with correct amount (behavior)
- Verify the refund object has status "completed" (state)
This gives confidence that both the external communication happened correctly and your system's internal state is consistent.
Avoid Over-Specification
Don't verify every single method call just because you can. Focus on the interactions that truly matter for the test's purpose. Too much behavior verification makes tests brittle.
Key Takeaway: Combining state and behavior verification provides comprehensive test coverage when you need to confirm both correct interactions and correct outcomes, but keep it focused on what truly matters to avoid brittle tests.