0
0
PyTesttesting~5 mins

Mock call assertions in PyTest

Choose your learning style9 modes available
Introduction

Mock call assertions help check if a fake function was called correctly during a test. This makes sure your code talks to other parts as expected.

When you want to test a function that calls another function without running the real one.
When you want to check if a function was called with the right inputs.
When you want to confirm how many times a function was called.
When you want to test error handling by simulating failures in called functions.
Syntax
PyTest
mock_function.assert_called()
mock_function.assert_called_once()
mock_function.assert_called_with(arg1, arg2)
mock_function.assert_called_once_with(arg1, arg2)
mock_function.assert_any_call(arg1)
mock_function.call_count

Use assert_called() to check if the mock was called at least once.

Use assert_called_with() to check the last call's arguments.

Examples
Checks if mock_func was called at least once.
PyTest
mock_func.assert_called()
Checks if mock_func was called exactly once with arguments 5 and 'test'.
PyTest
mock_func.assert_called_once_with(5, 'test')
Checks if mock_func was called at least once with argument 'hello'.
PyTest
mock_func.assert_any_call('hello')
Prints how many times mock_func was called.
PyTest
print(mock_func.call_count)
Sample Program

This test replaces the real greet function with a mock. It calls welcome_user with the mock and checks if the mock was called once with 'Alice'. It also prints how many times the mock was called.

PyTest
from unittest.mock import Mock

def greet(name):
    print(f"Hello, {name}!")

def welcome_user(greet_func, user_name):
    greet_func(user_name)

mock_greet = Mock()
welcome_user(mock_greet, 'Alice')

mock_greet.assert_called_once_with('Alice')
print(f"Call count: {mock_greet.call_count}")
OutputSuccess
Important Notes

Mock call assertions help test interactions without running real code.

Always check the call arguments to catch mistakes early.

Use call_count to verify how many times a mock was used.

Summary

Mock call assertions check if and how mocks were called.

They help test code interactions safely and clearly.

Common assertions include assert_called_with and assert_called_once_with.