Basic Mock Example - 3.3 | Chapter 10: Testing, Debugging, and Logging | Python Advance
K12 Students

Academics

AI-Powered learning for Grades 8–12, aligned with major Indian and international curricula.

Academics
Professionals

Professional Courses

Industry-relevant training in Business, Technology, and Design to help professionals and graduates upskill for real-world careers.

Professional Courses
Games

Interactive Games

Fun, engaging games to boost memory, math fluency, typing speed, and English skillsβ€”perfect for learners of all ages.

games

weather_service.py

def get_temperature(api_client):
return api_client.fetch_temperature("Delhi")
Now, to test this function without actually making a network call, use mocking:

python

test_weather_service.py

from weather_service import get_temperature
from unittest.mock import Mock

def test_get_temperature():
mock_api = Mock()
mock_api.fetch_temperature.return_value = 30

result = get_temperature(mock_api)

assert result == 30
mock_api.fetch_temperature.assert_called_once_with("Delhi")

πŸ” Breakdown:

Mock() creates a fake object that mimics the API.

return_value sets the result the mock should return.

assert_called_once_with() verifies correct interaction.

This is useful when the real service is slow, unreliable, or has side effects. Mocks allow you to write fast, reliable, and isolated tests.

🧠 Practice
Question: Why do we use mocks in unit testing?

Answer: Mocks are used to simulate the behavior of external dependencies like APIs, databases, or file systems, enabling us to test our code in isolation without relying on those actual services.

Hint: Think about scenarios where real dependencies might fail, slow down, or behave unpredictably.

Question: What does the following code do?

python

mock_api = Mock()
mock_api.get_status.return_value = "OK"

Answer: It creates a mock object with a method get_status that, when called, will always return "OK". This simulates a predictable response for testing.

Hint: Consider the method chaining and return value.

Question: How do you verify if a mock method was called with a specific argument?

Answer: Use mock_object.method.assert_called_once_with(arguments) to ensure the mock method was called exactly once with those arguments.

Hint: This is part of mock’s assertion methods.


Question: Why is mocking useful in unit testing?

Answer: Mocking helps isolate the unit of code being tested by replacing dependencies (like APIs or databases) with controlled, simulated objects. This makes tests faster, more reliable, and easier to write.

Hint: Think about components that are slow, unpredictable, or external.

Question: How can you simulate a method returning a specific value