我正在使用python的unittest.mock在Django应用程序中执行一些测试。我想检查一个类是否被调用,并且它的实例上的方法也被调用。模拟python单元测试中的类和类方法
例如,给定这个简化的示例代码:
# 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
不调用。我知道我错过了一些东西 - 嘲笑模拟课堂上的一种方法? - 但我不确定什么或如何使它工作。
Doh!我花了很长时间看着我认为我做错了嘲笑,我错过了那个愚蠢的错误!谢谢Jared。 –