Python unittest Mock patch object not methods

I'm having trouble checking unit testing with Mock in Python. I have a method start_thing()in the class that I would like to test:

class ComplexClass:
   def __init__(self, lots, of, args):
       self.lots = lots
       ..

   def start_thing(self):
        import pdb; pdb.set_trace()
        print "some error!!"
        assert False

The class to which this applies is rather complex and painful to try manually by layout. This is why I started looking at using Mock.

I would like to customize the layout that Mocks an instance of this class to make unittest easier to run, but not to mock the method start_thing()to test the real implementation start_thing(), not the mock version. so I created this:

class TestComplexClass(TestCase):
     @patch.object(module.ComplexClass, 'start_thing')
     def test_start_thing(self, mock_method):
        ComplexClass.start_thing()

, start_thing(), , - . ? ?

, , , , , , , , , , , .

, - Mock ?

+4
1

, , , :

class ComplexClassStub(ComplexClass):
  def __init__(self):
    self.lots = None
    self.the_rest_of_the_args = None # Now your complex class isn't so complex.

class ComplexClassTest(unittest.TestCase):
  def Setup(self):
    self.helper = ComplexClassStub()

  def testStartThing(self):
    with mock.patch.object(self.helper, 'SomethingToMock') as something_mocked:
      expected = 'Fake value'
      actual = self.helper.start_thing()
      self.assertEqual(expected, actual)
      something_mocked.assert_called_once_with()
+3

Source: https://habr.com/ru/post/1608242/


All Articles