Python unittest Mock补丁对象不是方法

时间:2015-09-20 22:07:33

标签: python python-2.7 unit-testing mocking python-unittest

我无法在Python中使用Mock进行单元测试。我在类I中有一个方法start_thing(),我想测试一下:

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

这个类属于非常复杂,并且尝试手动模拟很痛苦。这就是为什么我开始考虑使用Mock。

我想设置一个模拟Mocks这个类的一个实例,以便运行单元测试,但不要模拟方法start_thing(),以便测试真正的start_thing()实现,而不是一个模拟的版本..所以我创建了这个:

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

运行我的测试时,我的实际方法start_thing()中没有命中调试跟踪,断言或打印,这表明我已经模拟了类和方法 - 我只想模拟对象并测试真实方法。我在这做错了什么?这可能吗?

我发现很多Mock的例子展示了如何创建我想要测试的方法的模拟版本,我觉得这有点没用,因为我不想检查它是否存在正确调用,而不是我想在实际代码中测试实现,并模拟它所属的类,以便更容易创建。

也许我对整个模拟测试理念不了解?

1 个答案:

答案 0 :(得分:3)

我认为你不想嘲笑那个课程,而是将其存根,例如:

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()