securelms
Engineering
9 min read

Mocking/Patching Class & Instance variables in Python Testing

H
Hemachandra Routhu
Project Leader
Published On
April 10, 2025

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 attributes
2
Mocking instance attributes
3
The patch vs patch.object distinction

Using 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 5000

2. Mocking a Class Method

def test_get_cost(self):
    with patch("variables.Car.get_cost", return_value=10000):
        print(Car.get_cost()) # Prints 10000

Using 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 1000

2. 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 3000

Summary 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
Spread the Word
Browse More Articles