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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With