简体   繁体   中英

Mock patch specific instance of class

How to mock a specific instance of a class using patch ?

In my test file I have:

@classmethod
def setUpClass(cls):
    cls.instance_of_my_class = myClass()

one of the tests then calls a function in myClass that I wish to mock the return value of.

I can do so like this.

self.instance_of_my_class.cool_fuction = Mock(return_value=(True, True))

I wish to do this using with patch so that the mock does not persist into the other tests, or to, in some way unset the mock.

However, patch requires a string like "package.module.Class.attribute" as it's target so putting

with patch("self.instance_of_my_class") as mock:
      mock.return_value.cool_fuction.return_value = (True, True)

fails with traceback

AssertionError: No module named 'self'

If I patch the class like

with patch("functions_folder.my_script.myClass") as mock:
      mock.return_value.cool_fuction.return_value = (True, True)

the wrong instance is patched and mock.called returns False

The test looks like:

def test_foo_function(self):
    result = self.instance_of_my_class.foo_function()
    self.assertTrue(result[0]["confirmed"])

and foo_function calls on cool_function which I want to mock return (True, True)

Thanks to @johnsharpe for pointing out the answer.

with the same setUpClass at the start of Test_myClass as I had:

@classmethod
def setUpClass(cls):
    cls.instance_of_my_class = myClass()

working test case now looks like:

@patch.object(myClass, "cool_function")
def test_foo_function(self, mock):
    mock.return_value = (True, True)
    
    result = self.instance_of_my_class.foo_function()

    self.assertTrue(result[0]["confirmed"])
    self.assertTrue(mock.called)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM