我有以下情况:
在我的models.py
class FooBar(models.Model):
description = models.CharField(max_length=20)
在我的 utils.py 文件中。
from models import FooBar
def save_foobar(value):
'''acts like a helper method that does a bunch of stuff, but creates a
FooBar object and saves it'''
f = FooBar(description=value)
f.save()
在测试.py
from utils import save_foobar
@patch('utils.FooBar')
def test_save_foobar(self, mock_foobar_class):
save_mock = Mock(return_value=None)
mock_foobar_class.save = save_mock
save_foobar('some value')
#make sure class was created
self.assertEqual(mock_foobar_class.call_count, 1) #this passes!!!
#now make sure save was called once
self.assertEqual(save_mock.call_count, 1) #this fails with 0 != 1 !!!
这是我正在尝试做的事情的简化版本......所以请不要挂断为什么我有一个 utils 文件和一个辅助函数(在现实生活中它做了几件事)。另外,请注意,虽然简化了,但这是我的问题的实际工作示例。对 test call_count 的第一次调用返回 1 并通过。但是,第二个返回 0。所以,看起来我的补丁正在工作并被调用。
如何测试不仅创建了 FooBar 的实例,而且还调用了它的 save 方法?