Interaction-Based vs State-Based Testing
You'll learn: The two fundamental approaches to verifying test behavior—checking what happened versus checking how it happened.
The Core Distinction
When testing code, you can verify correctness in two ways:
State-based testing checks the result of an operation. After calling your code, you examine the final state—return values, object properties, database records—to confirm the outcome is correct.
Interaction-based testing checks the process of an operation. You verify that specific methods were called with expected arguments, in the right order, the correct number of times. This uses mocks and spies to record interactions.
A Practical Example
Imagine testing code that sends an email notification:
State-based approach:
- Check that the email appears in an outbox
- Verify the recipient's inbox contains the message
- Examine the email's subject and body content
Interaction-based approach:
- Verify
emailService.send()was called once - Check it received the correct recipient address
- Confirm the subject and body parameters were correct
When to Use Each
Choose state-based testing when:
- The outcome is easily observable
- You want tests resilient to implementation changes
- Testing pure functions or simple transformations
Choose interaction-based testing when:
- Side effects matter (logging, external API calls)
- The state is hard to observe or verify
- You're testing at boundaries where real implementations are costly
The Balance
State-based tests are generally more maintainable—they don't break when you refactor internal implementation details. Interaction-based tests couple more tightly to how code works, making them fragile but valuable for verifying critical integrations.
Key Takeaway: State-based testing verifies outcomes (what changed), while interaction-based testing verifies behavior (what methods were called). Prefer state-based when possible, use interaction-based at boundaries and for side effects.