0
0
PyTesttesting~15 mins

Mock call assertions in PyTest - Build an Automation Script

Choose your learning style9 modes available
Verify mock function call and arguments using pytest
Preconditions (2)
Step 1: Create a mock object for the dependent function
Step 2: Call the main function that uses the mock
Step 3: Assert that the mock was called exactly once
Step 4: Assert that the mock was called with the expected arguments
✅ Expected Result: Test passes confirming the mock function was called once with the correct arguments
Automation Requirements - pytest with unittest.mock
Assertions Needed:
assert mock_function.called is True
assert mock_function.call_count == 1
assert mock_function.call_args == expected_args
Best Practices:
Use patch decorator or context manager to mock dependencies
Use explicit assertions for call count and call arguments
Keep tests isolated and independent
Automated Solution
PyTest
from unittest.mock import Mock, patch
import pytest

# Function to test

def greet_user(user_service, user_id):
    user_name = user_service.get_user_name(user_id)
    return f"Hello, {user_name}!"

# Test function
@patch('test_module.UserService')
def test_greet_user_calls_get_user_name(mock_user_service_class):
    # Arrange
    mock_user_service = Mock()
    mock_user_service.get_user_name.return_value = 'Alice'
    mock_user_service_class.return_value = mock_user_service
    user_id = 42

    # Act
    from test_module import greet_user
    result = greet_user(mock_user_service, user_id)

    # Assert
    assert mock_user_service.get_user_name.called is True
    assert mock_user_service.get_user_name.call_count == 1
    mock_user_service.get_user_name.assert_called_with(user_id)
    assert result == 'Hello, Alice!'

The test uses patch to replace UserService with a mock object.

We create a mock instance and set the return value for get_user_name.

We call the greet_user function with the mock and a user ID.

Assertions check that get_user_name was called once with the correct argument.

Finally, we verify the returned greeting string is as expected.

Common Mistakes - 3 Pitfalls
Not asserting the call count, only checking if called
Using hardcoded arguments in assertions without matching the actual call
Not using patch or mock properly, leading to real function calls
Bonus Challenge

Now add data-driven testing with 3 different user IDs and expected names

Show Hint