简体   繁体   English

Python unittest Mock补丁对象不是方法

[英]Python unittest Mock patch object not methods

I am having trouble getting my head around unit testing with Mock in Python. 我无法在Python中使用Mock进行单元测试。 I have a method start_thing() in a class I'd like to test: 我在一个我想测试的类中有一个方法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

The class this belongs to is quite complex and a pain to try and mock manually. 这个类属于非常复杂,并且尝试手动模拟很痛苦。 That is why I started to look at using Mock. 这就是为什么我开始考虑使用Mock。

I would like to setup a mock that Mocks an instance of this class to make it easy to run a unittest, but not mock the method start_thing() so that the real start_thing() implementation is tested, not a mocked version .. so I created this: 我想设置一个模拟Mocks这个类的一个实例,以便运行单元测试,但不是模拟方法start_thing()以便测试真正的start_thing()实现,而不是模拟版本..所以我创造了这个:

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

When running my test the debug trace, assert or print are not hit in my real method start_thing() , which suggests I have mocked the class and the method - where I just want to mock the object and test the real methods. 在运行我的测试时,我的实际方法start_thing()中没有命中调试跟踪,断言或打印,这表明我已经模拟了类和方法 - 我只想模拟对象并测试实际方法。 What am I doing wrong here? 我在这做错了什么? Is that possible? 那可能吗?

I have found lots of examples with Mock showing how to create a mock version of the method I want to test, which I think is kind of pointless since I don't want to check if it's being called correctly, rather I want to test the implementation in the real code, and mock the class it belongs to so it's easier to create. 我发现很多Mock的例子展示了如何创建我想要测试的方法的模拟版本,我认为这是毫无意义的,因为我不想检查它是否被正确调用,而是我想测试在真实代码中实现,并模拟它所属的类,因此更容易创建。

Perhaps there's something I don't understand about the Mock testing idea as a whole? 也许我对整个Mock测试理念有些不了解?

I don't think you want to mock that class but to stub it out, ex: 我不认为你想要嘲笑那个课程,但要把它剔除,ex:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM