Course contentsShow
← Python
Lesson 763 of 1,06012. Testing and DebuggingFree lesson

Verifying Interaction Patterns with Mocks

Master the use of mock objects to verify that specific methods are called with the correct arguments during test execution.

In this lesson, you will learn how to verify that your code interacts with external dependencies exactly as intended by inspecting the history of calls made to a mock object.

Beyond Simple Stubs

Previously, we discussed using mock objects as "stubs" to provide predictable return values for our tests. However, testing is often just as much about the action as it is about the result. When a function communicates with an external system—like sending an email or saving a file—you need to ensure that the communication itself happens correctly. You don't just want to know if the code ran; you want to verify that it was called with the specific arguments your business logic requires.

Inspecting Interaction Patterns

The unittest.mock library provides powerful assertion methods that allow us to "spy" on an object. After your code under test executes, you can query the mock to see if it was called, how many times it was called, and precisely which arguments were passed.

Consider a service that processes payments and logs them to a database:

from unittest.mock import Mock

def process_payment(gateway, amount):
    gateway.charge(amount, currency="USD")

def test_payment_interaction():
    # Arrange
    mock_gateway = Mock()
    
    # Act
    process_payment(mock_gateway, 100)
    
    # Assert
    # Verify the method was called once
    mock_gateway.charge.assert_called_once()
    
    # Verify it was called with specific arguments
    mock_gateway.charge.assert_called_with(100, currency="USD")

In this example, assert_called_with acts as a guardrail. If process_payment had accidentally called the gateway with a different currency or an incorrect amount, the test would immediately fail. This is significantly more robust than simply checking if the function returned None or completed without crashing.

By focusing on these interaction patterns, you ensure that your code doesn't just produce the right output, but also behaves correctly within the larger architecture of your application. You are verifying the "contract" between your logic and its dependencies.

Key Takeaway: Use mock assertion methods like assert_called_with to ensure your code communicates with external dependencies using the exact arguments and patterns your application requires.