Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unittest.mock.patch: Context manager vs setUp/tearDown in unittest

There seems to be 2 ways to use unittest.mock.patch: is one way better?

Using a context manager and with statement:

class MyTest(TestCase):
    def test_something(self):
        with patch('package.module.Class') as MockClass:
            assert package.module.Class is MockClass

Or calling start and stop from setup and tearDown/cleanup:

class MyTest(TestCase):
    def setUp(self):
        patcher = patch('package.module.Class')
        self.MockClass = patcher.start()
        self.addCleanup(patcher.stop)

    def test_something(self):
        assert package.module.Class is self.MockClass

The context manager version is less code, and so arguable easier to read. I there any reason why I should prefer to use the TestCase setUp/tearDown infrastructure?

like image 425
Gary van der Merwe Avatar asked Sep 29 '22 18:09

Gary van der Merwe


1 Answers

The main reason to prefer patching in the setUp would be if you had more than one test that needed that class patched. In that case, you'd need to duplicate the with statement in each test.

If you only have one test that needs the patch, I'd prefer the with statement for readability.

like image 189
babbageclunk Avatar answered Oct 03 '22 02:10

babbageclunk