6

我有以下情况:

在我的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 方法?

4

1 回答 1

8

这是您的问题,您目前有:

mock_foobar_class.save = save_mock

因为mock_foobar_class是一个模拟的类对象,并且该save方法是在该类的实例(而不是类本身)上调用的,所以您需要断言 save 是在类的返回值(又名实例)上调用的。

试试这个:

mock_foobar_class.return_value.save = save_mock

我希望这会有所帮助!

于 2012-05-14T14:16:19.900 回答