HOME BLOG

Archive for August, 2020

How to do mocking in setUp in Python

Posted on: August 29th, 2020 by Olu No Comments

Hi folks,

In this post I will talk about how to mock functions in Python across all methods of your test class.

To do this, all you have to do is perform your mocking in the setUp method of your test class.

A way to do this is to create a patch object using code like:

mock_item_patch = mock.patch('some.module.path.item')

 

Next, call start() on the patch object to create your mock using code like

mock_item = mock_item_patch.start()

 

Once you do this, you can set return_value or side_effect as needed. E.g.

mock_item.foo.return_value = 'bar'

 

Don’t forget to add a call to stop the patch on clean-up using code

self.addCleanup(mock_item_patch.stop)

 

Below is code showing all these in action.

 

from unittest import mock, TestCase


class YourTestClass(TestCase):
    def setUp(self):
        mock_item_patch = mock.patch('some.module.path.item')
        mock_item = mock_item_patch.start()
        mock_item.foo.return_value = 'bar'
        self.addCleanup(mock_item_patch.stop)


    def test_something(self):
        ...

 

That’s all for now. Happy software development.