1

第一次使用 MagicMock,我想我自己都搞糊涂了。

测试一个 django 项目,所以在一个名为的文件中,services.py我有这些重要元素(非常简化,当然还有很多位)::

from django.template.loader import get_template

class Email:
    def send_success_attempt_email(self):
        template = get_template('emails/foo.html')

我想测试当send_success_attempt_email被调用时,get_template用正确的参数调用。所以我用补丁写了一个测试:

@patch('django.template.loader.get_template')
def test_email_template_should_be_used(self, get_template):
    email = Email()
    email.send_success_attempt_email()
    print(get_template.call_count)
    get_template.assert_called_with('emails/foo.html')

打印0call_count, 并吐出

AssertionError nose.proxy.AssertionError: 
Expected call: get_template('emails/foo.html')
Not called

我已经看到一个常见的陷阱是修补错误的实例,但我已经尝试了补丁的许多变体(例如,@patch('services.get_template')),但是虽然这改变了错误(nose.proxy.EncodeError: Can't pickle <class 'unittest.mock.MagicMock'>: it's not the same object as unittest.mock.MagicMock),但它并没有减轻它。

我知道我一定有一个根本性的误解。它是什么?

4

0 回答 0