首页 > 解决方案 > 如何模拟返回用户对象的函数

问题描述

我正在尝试模拟一个返回用户对象的方法,如下所示

@mock.patch('impersonate.helpers.which_user', return_value=self.user2)
    def test_user_can_retrieve_favs_using_impersonation(self):

它因错误而失败:NameError: name 'self' is not defined . 我self.user2在测试类的 setup 方法中定义了。

标签: python-3.xdjangopython-unittestdjango-testing

解决方案


您不能self在装饰器中使用 - 对象在解析时尚未定义。

相反,您可以将补丁移到方法中:

def test_user_can_retrieve_favs_using_impersonation(self):
    with mock.patch('impersonate.helpers.which_user', return_value=self.user2):
        ...

或者

def test_user_can_retrieve_favs_using_impersonation(self):
    with mock.patch('impersonate.helpers.which_user') as mocked: 
        mocked.return_value=self.user2
        ...

推荐阅读