Master Python Mock: Simulate External Calls for Seamless Unit Testing

This article explains what the Python Mock library does, how to install and import it, demonstrates basic and advanced usage including creating mock objects, setting return values and side effects, and shows how to apply patch and patch.object for effective unit testing without a real server.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Mock: Simulate External Calls for Seamless Unit Testing

What is Mock?

Mock is a Python library for supporting unit tests by replacing objects with mock objects to simulate behavior.

Assume a project a with module b containing function c that sends a request to a server and processes the JSON response; how can you unit test a.b.c without a real server?

Mock can replace the requests.get call so that the function returns a controlled value without involving a server.

Installation and Import

For Python versions before 3.3, install the library via pip: sudo pip install mock Then import it with: import mock From Python 3.3 onward, Mock is part of the standard library as unittest.mock and can be imported with:

from unittest import mock

Mock Objects

Basic usage

Mock objects are instances of the Mock class that can replace functions, classes, or instances to simulate their behavior. The class definition is roughly:

class Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, ...)

Typical workflow:

Identify the object to replace (e.g., a function or class).

Instantiate a Mock and set its behavior (return value, side effect, etc.).

Patch the target with the mock object.

Run test code and assert that the behavior matches expectations.

Example client code:

# client.py
import requests

def send_request(url):
    r = requests.get(url)
    return r.status_code

def visit_ustack():
    return send_request('http://www.ustack.com')

Example test cases using mock:

# test_client.py
import unittest
import mock
import client

class TestClient(unittest.TestCase):
    def test_success_request(self):
        success_send = mock.Mock(return_value='200')
        client.send_request = success_send
        self.assertEqual(client.visit_ustack(), '200')

    def test_fail_request(self):
        fail_send = mock.Mock(return_value='404')
        client.send_request = fail_send
        self.assertEqual(client.visit_ustack(), '404')

Mock objects provide attributes such as called to check if they were invoked, and call_args to inspect the arguments passed.

Advanced usage

Mock class parameters

name : Identifier for the mock, useful for debugging.

return_value : Value returned when the mock is called (if side_effect does not override).

side_effect : Callable that determines the mock’s return value or raises an exception.

Automatic creation of attributes

Accessing an undefined attribute on a mock automatically creates a child mock, which is handy for multi‑level attribute mocking.

patch and patch.object

The patch and patch.object functions return a mock instance and can be used as decorators, context managers, or class decorators to limit the scope of mocking.

with mock.patch('client.send_request', success_send):
    from client import visit_ustack
    self.assertEqual(visit_ustack(), '200')
patch.object

works similarly but specifies the target object and attribute explicitly.

How to learn Mock?

Understand what mock can do, read the official documentation, and practice by applying it in your own unit tests.

Official documentation

Python 2.7

http://www.voidspace.org.uk/python/mock/index.html

Python 3.4

https://docs.python.org/3.4/library/unittest.mock-examples.html

https://docs.python.org/3.4/library/unittest.mock.html

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Mockpatchunittestunit-testing
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.