Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use unittest.mock.patch to replace a dependency where your code looks it up, then configure the replacement with return_value or side_effect. Keep the patch scoped to a decorator or with block, and use autospec when you want the mock to enforce the real object’s attributes and call signature.

A minimal example

Suppose service.py imports a function directly from a gateway module:

# service.py
from gateway import fetch_record

def label_for(record_id):
    record = fetch_record(record_id)
    return record["label"].upper()

Patch the name in service, because that is where label_for looks it up:

# test_service.py
from unittest import TestCase
from unittest.mock import patch

from service import label_for

class LabelTests(TestCase):
    @patch("service.fetch_record", autospec=True)
    def test_label_for_uppercases_label(self, fetch_record):
        fetch_record.return_value = {"label": "sample"}

        result = label_for("r-17")

        self.assertEqual(result, "SAMPLE")
        fetch_record.assert_called_once_with("r-17")

The test controls the dependency’s response, checks the returned behavior, and verifies the identifier passed to the dependency. patch restores the original name when the decorated test finishes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Patch the name the code under test uses

A common mistake is patching the function where it was originally defined rather than the name imported by the module being tested. With from gateway import fetch_record, service holds its own reference to fetch_record; patch service.fetch_record. If the code instead uses import gateway and calls gateway.fetch_record(...), patch the attribute at that lookup path.

patch can be used as a decorator or a context manager. Both limit the replacement to a specific scope and restore the original afterward:

from unittest.mock import patch

with patch("service.fetch_record", autospec=True) as fetch_record:
    fetch_record.return_value = {"label": "sample"}
    result = service.label_for("r-17")

Use patch.object(obj, "attribute") when you already have the object whose attribute should be replaced. Use patch.dict(mapping, ...) to temporarily change mapping contents; patch.multiple can replace several attributes together.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Choose a mock and configure its behavior

Mock for ordinary calls

Mock records calls and creates attributes as they are accessed. Set return_value when the dependency should return one fixed result whenever called:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
fetch_record.return_value = {"label": "sample"}

Calling the mock returns that value. This is usually the clearest setup for a deterministic dependency response.

MagicMock for Python protocols

MagicMock is a Mock variant with common magic methods pre-created. Use it when the replacement is used through a protocol such as iteration, indexing, or len(). For a dependency that is simply called and returns a value, a regular Mock is generally sufficient.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

side_effect for errors, sequences, or conditional results

Use side_effect to model behavior beyond one fixed return value. It can be an exception class or instance, a function, or an iterable of successive outcomes:

# Raise an error
fetch_record.side_effect = TimeoutError

# Return successive values on successive calls
fetch_record.side_effect = [
    {"label": "first"},
    {"label": "second"},
]

# Compute a response from the arguments
def response_for(record_id):
    return {"label": record_id}

fetch_record.side_effect = response_for

When an iterable side effect runs out, another call raises StopIteration. Make the sequence long enough for the calls the test expects, or use a function when behavior should depend on arguments.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use autospec when calls should match the real API

A permissive mock can accept misspelled attributes and calls that the real dependency would reject. Passing autospec=True to patch constrains available attributes and checks function call signatures. create_autospec() offers the same kind of API-aware mock when creating one directly. For stricter attribute assignment, use spec_set=True; it disallows assigning attributes absent from the specification.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
from unittest.mock import create_autospec

mock_fetch = create_autospec(fetch_record)
mock_fetch.return_value = {"label": "sample"}

Autospec relies on introspection. It may not suit objects that create attributes dynamically or whose attribute access has side effects. In those cases, a less restrictive mock or a small handwritten fake may be more reliable and easier to understand.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test behavior and meaningful interactions

Prefer assertions about the result or externally visible behavior. Assert calls when the interaction is part of the contract—for example, that the correct record identifier is passed, or that a second request is avoided. Avoid making a test depend on incidental internal call details that can change without changing the behavior the test is meant to protect.

Mocks are useful when a dependency is expensive, nondeterministic, or outside the unit’s responsibility. If a small deterministic object can express the needed behavior more clearly, use a handwritten fake instead. The choice is about clarity and isolation, not a rule that every dependency must be mocked.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Mock asynchronous functions

When patch creates a replacement for an asynchronous function and no replacement is supplied, it uses AsyncMock by default. Async mocking behavior can have version-specific details, so check the documentation for the Python version used by your project before relying on a particular assertion or configuration API.

Troubleshoot common mock failures

  • The real dependency still runs: patch the name resolved by the module under test, not automatically the name in the dependency’s defining module. Check whether the code used a direct import or a module-qualified attribute.
  • The original dependency stays replaced beyond the test: limit the patch with a decorator or context manager so it is automatically restored at scope exit.
  • A mock accepts a typo or impossible call: use autospec=True or create_autospec() to constrain attributes and function signatures. Consider spec_set=True when assignments to unknown attributes should also fail.
  • Autospec fails or misses a dynamic attribute: introspection may not reflect runtime-created attributes and can trigger unsafe attribute access. Use a suitable simpler mock or a handwritten fake instead.
  • A later call raises StopIteration: an iterable side_effect has been exhausted. Add the expected outcome or replace the iterable with a function that determines the response.

Or skip the browser setup

Mocking Python dependencies does not require a browser. If your task also needs website screenshots, ScreenshotNeo is a separate screenshot API and MCP server; it is not a replacement for unittest.mock. Its one-request API example is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie/consent banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Its MCP server provides screenshot and page-information tools for AI agents. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Sign up for ScreenshotNeo’s free plan.

Frequently Asked Questions

Does Python include unittest.mock?

Yes. The unittest.mock module has been included in Python since Python 3.3.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can a mock be used as a context manager?

Yes, if the code under test uses context-manager methods, use a MagicMock or configure an appropriate replacement that implements the required protocol.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.