title: How to use class patch decorator in unittest.TestCase setUp method
body: <p>I am currently writing test coverage for a wrapper around sqlite3 in Python. At present my code looks something like this:</p>
  
  <pre><code>import unittest
  from unittest.mock import patch
  from MemberDatabase import MemberDatabase
  
  @patch('sqlite3.connect')
  class MemberDatabaseTestCase(unittest.TestCase):
      def test_dbConnect(self, mocksql_connect):
          mdb = MemberDatabase('test.db')
          mocksql_connect.assert_called_with('test.db')
  
      def test_optionalCommit(self, mocksql_connect):
          mdb = MemberDatabase('test.db')
          mdb.optionalCommit()
          self.assertTrue(mocksql_connect().commit.called)
  </code></pre>
  
  <p>Various other tests follow which all create <code>mdb</code> in the same way. The constructor of <code>MemberDatabase</code> calls <code>sqlite3.connect()</code>. I would like to tidy the test case up by moving the assignment of <code>mdb</code> to <code>setUp()</code>. However, <code>sqlite3.connect()</code> isn't mocked in <code>setUp()</code> so this results in the actual <code>sqlite3.connect()</code> being called and a real database connection being created.</p>
  
  <p>Is there any way to use the patched <code>sqlite3.connect()</code> in <code>setUp()</code>? Perhaps I need to create the mock inside <code>setUp()</code> instead of using the decorator, but I think the code is cleaner using the decorator approach. Also, I read that if I create mock</p>