Engineering
9 min read
Mocking/Patching Class & Instance variables in Python Testing
H
Hemachandra Routhu
Project Leader
Published On
April 10, 2025
Mocking Mastery
Class & Instance Variables
Introduction
This article provides an overview of how to use the unittest module to mock or patch class and instance variables within a Python class. Understanding the distinction between patch and patch.object is critical for writing robust unit tests.
1
Patching class attributes2
Mocking instance attributes3
The patch vs patch.object distinctionUsing patch()
1. Mocking a Class Attribute
test_variables.py
from unittest.mock import patch
from variables import Car
class TestCar:
def test_value_with_patch(self):
with patch('variables.Car.cost', 5000):
print(Car.cost) # Prints 50002. Mocking a Class Method
def test_get_cost(self):
with patch("variables.Car.get_cost", return_value=10000):
print(Car.get_cost()) # Prints 10000Using patch.object()
1. Mocking an Instance Variable
def test_insurance_variable(self):
car1 = Car()
with patch.object(car1, "insurance", new=1000):
print(car1.insurance) # Prints 10002. Mocking an Instance Method
def test_insurance_method(self):
car = Car()
with patch.object(car, "get_insurance", return_value=3000):
print(car.get_insurance()) # Prints 3000Summary of Patching Patterns
patch()
- • High-level function
- • Targets attributes of classes
- • Uses string paths
patch.object()
- • Targeted instance function
- • Targets specific object instances
- • Avoids global side-effects
Until then, your friend here, Hemachandra, is signing off…
For more courses, visit my website here.
Stay ahead of the curve
Get the latest technical insights on Python, Security, and Cloud Architecture delivered to your inbox.
Spread the Word
Browse More Articles