像这样调用模拟对象,my_class().my_method.assert_called_once_with(num=10) ^^I'm using python's unittest.mock to do some testing in a Django app. I want to check that a class is called, and that a method on its instance is also called.For example, given this simplified example code:# In project/app.pydef do_something(): obj = MyClass(name='bob') return obj.my_method(num=10)And this test to check what's happening:# In tests/test_stuff.py@patch('project.app.MyClass')def test_it(self, my_class): do_something() my_class.assert_called_once_with(name='bob') my_class.my_method.assert_called_once_with(num=10)The test successfully says that my_class is called, but says my_class.my_method isn't called. I know I'm missing something - mocking a method on the mocked class? - but I'm not sure what or how to make it work. 解决方案 Your second mock assertion needs to test that you are calling my_method on the instance, not on the class itself.Call the mock object like this,my_class().my_method.assert_called_once_with(num=10) ^^ 这篇关于在python单元测试中模拟一个类和一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-30 10:28