Verify mock function call and arguments using pytest
Preconditions (2)
✅ Expected Result: Test passes confirming the mock function was called once with the correct arguments
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.
Now add data-driven testing with 3 different user IDs and expected names
assert_called_with method check in pytest mocks?assert_called_withassert_called_once_with, it does not require the call to be exactly once, just that the last call had those arguments.assert_called_once_with.from unittest.mock import Mock mock = Mock() mock(1, 2) mock(3, 4) mock.assert_called_with(3, 4)
from unittest.mock import Mock mock = Mock() mock(10) mock.assert_called_once(10)
assert_called_once checks the call count but does not accept arguments to check call parameters.assert_called_once_with should be used instead.(1, 'a'), (2, 'b'), (3, 'c')assert_has_calls with a list of expected calls and any_order=False is used.mock.assert_called() only checks if it was called at least once without verifying arguments or order. Chaining mock.assert_called_with(1, 'a') and mock.assert_called_with(3, 'c') checks some arguments but not all calls, order, or completeness. mock.assert_called_once_with(3, 'c') checks only that there was exactly one call with those arguments.Pass the test and this pattern moves unknown