Python unittest 模拟补丁对象不是方法

Python unittest Mock patch object not methods

我无法在 Python 中使用 Mock 进行单元测试。我在 class 中有一个方法 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

它所属的 class 非常复杂,并且很难手动尝试和模拟。这就是我开始考虑使用 Mock 的原因。

我想设置一个 mock 来模拟这个 class 的一个实例,以便于 运行 单元测试,但不模拟方法 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() 中测试调试跟踪、断言或打印时,这表明我已经模拟了 class 和方法 - 其中我只想模拟对象并测试真正的方法。我在这里做错了什么?这可能吗?

我发现了很多 Mock 示例,展示了如何创建我想要测试的方法的模拟版本,我认为这有点毫无意义,因为我不想检查它是否被正确调用,而是我想在真实代码中测试实现,并模拟它所属的 class 以便更容易创建。

对于整个 Mock 测试的想法,也许我有一些不理解的地方?

我不认为你想嘲笑那个 class 而是想把它去掉,例如:

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