title: unittest.mock.patch: Context manager vs setUp/tearDown in unittest
body: <p>There seems to be 2 ways to use <a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch" rel="nofollow noreferrer">unittest.mock.patch</a>: is one way better?</p>
  
  <p>Using a context manager and with statement:</p>
  
  <pre><code>class MyTest(TestCase):
      def test_something(self):
          with patch('package.module.Class') as MockClass:
              assert package.module.Class is MockClass
  </code></pre>
  
  <p>Or calling start and stop from setup and tearDown/cleanup:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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?</p>