Test Overview
This test uses MagicMock to simulate a database call. It verifies that the mocked method is called once and returns the expected value.
This test uses MagicMock to simulate a database call. It verifies that the mocked method is called once and returns the expected value.
from unittest.mock import MagicMock import pytest class Database: def get_user(self, user_id): # Imagine this method talks to a real database pass def test_get_user_called_once(): db = Database() db.get_user = MagicMock(return_value={'id': 1, 'name': 'Alice'}) result = db.get_user(1) db.get_user.assert_called_once_with(1) assert result == {'id': 1, 'name': 'Alice'}
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Test environment is ready with pytest and unittest.mock imported | - | PASS |
| 2 | Create Database instance and replace get_user with MagicMock returning a user dict | Database instance created; get_user method mocked to return {'id': 1, 'name': 'Alice'} | - | PASS |
| 3 | Call mocked get_user method with argument 1 | get_user called with 1, returns {'id': 1, 'name': 'Alice'} | Check that get_user was called once with argument 1 | PASS |
| 4 | Assert that get_user was called exactly once with argument 1 | Mock records one call with argument 1 | db.get_user.assert_called_once_with(1) passes | PASS |
| 5 | Assert that the returned result matches the expected dictionary | Result is {'id': 1, 'name': 'Alice'} | assert result == {'id': 1, 'name': 'Alice'} passes | PASS |