0
0
PyTesttesting~10 mins

Mock and MagicMock in PyTest - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - pytest
PyTest
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'}
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startsTest environment is ready with pytest and unittest.mock imported-PASS
2Create Database instance and replace get_user with MagicMock returning a user dictDatabase instance created; get_user method mocked to return {'id': 1, 'name': 'Alice'}-PASS
3Call mocked get_user method with argument 1get_user called with 1, returns {'id': 1, 'name': 'Alice'}Check that get_user was called once with argument 1PASS
4Assert that get_user was called exactly once with argument 1Mock records one call with argument 1db.get_user.assert_called_once_with(1) passesPASS
5Assert that the returned result matches the expected dictionaryResult is {'id': 1, 'name': 'Alice'}assert result == {'id': 1, 'name': 'Alice'} passesPASS
Failure Scenario
Failing Condition: The mocked method get_user is not called or called with wrong arguments
Execution Trace Quiz - 3 Questions
Test your understanding
What does MagicMock do in this test?
ARaises an error when get_user is called
BSimulates the get_user method to return a fake user without calling the real method
CCalls the real database to get user data
DDeletes the get_user method from the Database class
Key Result
Use MagicMock to replace real methods when you want to test code behavior without relying on external systems. Always verify the mock was called as expected to ensure your test is meaningful.