Skip to main content

31. Mocking and Patching

Mocking replaces parts of the system under test with controlled objects.


Using unittest.mock

from unittest.mock import patch

def get_data():
import requests
return requests.get("http://example.com").text

@patch("requests.get")
def test_get_data(mock_get):
mock_get.return_value.text = "mocked"
assert get_data() == "mocked"

Wrap-Up

Mocking allows isolating code under test from external dependencies.