Skip to content Skip to sidebar Skip to footer

Mocking Instance Attributes

Please help me understand why the following doesn't work. In particular - instance attributes of a tested class are not visible to Python's unittest.Mock. In the example below bar

Solution 1:

Patching is used to modify name or attribute lookup. In this case, there is no bar attribute of the class temp.Foo.

If the intent is to patch the instance variable, you either need an existing instance to modify

deftest(self):
    f = Foo()
    with patch.object(f, 'bar', 3):
        self.assertEqual(f.bar, 3)

or you may want to patch the function call that initializes the instance attribute in the first place.

deftest(self):
    with patch('some_external_function_returning_list', return_value=3):
        f = Foo()
    self.assertEqual(f.bar, 3)

Post a Comment for "Mocking Instance Attributes"