Course contentsShow
← Software Engineering
Lesson 483 of 1,93314. Test DoublesFree lesson

Behavior Verification: Testing Interactions

Understand how to verify that correct methods were called with expected arguments using mocks.

Behavior Verification: Testing Interactions

What you'll learn: How to verify that your code calls the right methods with the correct arguments, not just what it returns.

The Core Idea

So far, you've learned about state verification — checking that functions return the right values or that objects end up in the correct state. Behavior verification is different: it tests how your code interacts with its dependencies, not just what it produces.

Think of it like this: State verification checks if someone successfully sent an email (did the message appear in the "sent" folder?). Behavior verification checks if they actually called the email service with the right recipient and message — even if you can't see the final sent folder.

Why This Matters

When testing code that depends on external systems (databases, APIs, payment processors), you often can't check final outcomes directly in a test. Instead, you verify that your code called the right methods on its collaborators.

This is where mocks shine. A mock lets you:

  1. Set expectations: "I expect sendEmail to be called once with these arguments"
  2. Execute your code: Run the function being tested
  3. Verify interactions: Check that the expected calls actually happened

Example Scenario

Imagine testing a PlaceOrder function that should charge a payment processor. You don't want to make real charges in tests! Instead, you use a mock payment processor and verify:

  • Was charge() called?
  • Was it called with the correct amount?
  • Was it called exactly once?

The mock records these interactions during the test, and you verify them afterward using the mock framework's verification methods.

Key Takeaway: Behavior verification uses mocks to confirm your code calls the right methods with expected arguments, ensuring proper interaction with dependencies even when final outcomes aren't visible in tests.