Concept Explanation
Imagine you are testing a function that sends a real email to a customer. If you run your tests 100 times, you don't want to actually send 100 emails! Or imagine you are testing a function that reads the current weather from an API. If the API is down, your tests will fail even if your code is perfect.
Mocking is the act of replacing a "real" object with a "fake" one. The fake object (the Mock) looks like the real one, but it doesn't actually send emails or talk to the internet. Instead, it just records what happened so you can verify: "Yes, my code tried to send an email."
Syntax or Core Structure
The Mock Object
Python's built-in unittest.mock library is the standard tool.
from unittest.mock import Mock
# 1. Create a fake object
fake_api = Mock()
# 2. Tell it what to return
fake_api.get_user_name.return_value = "Harsh"
# 3. Use it!
name = fake_api.get_user_name(101)
print(name) # "Harsh"
# 4. Verify it was called correctly
fake_api.get_user_name.assert_called_with(101)
Code Example #1 (Basic)
Using patch to temporarily replace a library.
from unittest.mock import patch
import requests
def get_status(url):
r = requests.get(url)
return r.status_code
# We 'patch' the requests.get function so it doesn't actually go online
@patch('requests.get')
def test_get_status(mock_get):
# Set the fake response
mock_get.return_value.status_code = 200
assert get_status("http://test.com") == 200
mock_get.assert_called_once()
Real World Example
Testing a Credit Card Processor: You obviously can't charge a real card during a test. You mock the payment gateway.
# 🏢 Logic Summary
# 1. Patch the 'charge_card' function of your payment library.
# 2. Configure the mock to return 'Success' for one test and 'Declined' for another.
# 3. Verify that your app shows the correct message to the user in both cases.
Common Mistakes
- Over-Mocking: If you mock everything, you aren't testing your real code anymore! Only mock things that are slow, expensive, or outside your control (like APIs or Databases).
- Wrong Patch Path: If you have
from my_app import db, you must patchmy_app.db, not justdb. This is the most common reason mocks fail to work. - Forgetting Assertions: Beginners often mock something but forget to check
assert_called_with(). The mock prevents the side effect, but you still need to verify your code used the mock correctly.
Practice Exercises
- The Time Traveler: Mock the
datetimemodule so that your test thinks "today" is January 1st, 2000. - The API Fake: Mock a
requests.postcall that returns a JSON error message. Verify that your function handles the error without crashing. - Call Counter: Write a script that calls a function 3 times. Use a Mock to verify that the function was indeed called exactly 3 times.