Mocking a class attribute


I have a class with a single class attribute that I want to mock

class MyClass:

    __attribute = ['123', '456']

import pytest
from directory.my_class import MyClass

def test_1(mocker):
    with mocker.patch.object(MyClass, '__attribute', {'something': 'new'}):
        test = MyClass()

I get:

E           AttributeError: <class 'directory.my_class.MyClass'> does not have the attribute '__attribute'

I also get the same error when trying:

def test_2(mocker):
    with mocker.patch('directory.my_class.MyClass.__attribute', new_callable=mocker.PropertyMock) as a:
        a.return_value = {'something': 'new'}
        test = MyClass()

I’ve also tried a direct assignment along with the other suggestions in this post:
Better way to mock class attribute in python unit test

My project is using a mocker fixture from this plugin:


You can do above with a PropertyMock

from unittest.mock import patch, PropertyMock

class MyClass:
  attr = [1, 2, 3]

with patch.object(MyClass, "attr", new_callable=PropertyMock) as attr_mock:
  attr_mock.return_value = [4, 5, 6]

  print(MyClass.attr) # prints [4, 5, 6]

print(MyClass.attr) # prints [1, 2, 3]

For a docs reference:

Answered By – Eelke van den Bos

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published