我正在使用 python 的 unittest.mock 在 Django 应用程序中进行一些测试。我想检查一个类是否被调用,以及它的实例上的方法是否也被调用。
例如,给出这个简化的示例代码:
# In project/app.py
def do_something():
obj = MyClass(name='bob')
return obj.my_method(num=10)
这个测试是为了检查发生了什么:
# 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)
测试成功表明my_class
被称为,但说my_class.my_method
没有被调用。我知道我错过了一些东西 - 模拟模拟类上的方法? - 但我不确定什么或如何让它发挥作用。
您的第二个模拟断言需要测试您正在调用my_method
on the instance,而不是班级本身。
像这样调用模拟对象,
my_class().my_method.assert_called_once_with(num=10)
^^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)