Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 调用实例变量AttributeError的测试类方法_Python_Mocking - Fatal编程技术网

Python 调用实例变量AttributeError的测试类方法

Python 调用实例变量AttributeError的测试类方法,python,mocking,Python,Mocking,当类使用实例变量时,如何模拟类来单独测试其方法?这是我试图测试的代码的一个示例 class Employee: def __init__(self, id): self.id = id self.email = self.set_email() def set_email(): df = get_all_info() return df[df[id] == self.id].email[0] def get_al

当类使用实例变量时,如何模拟类来单独测试其方法?这是我试图测试的代码的一个示例

class Employee:
    def __init__(self, id):
        self.id = id
        self.email = self.set_email()

    def set_email():
        df = get_all_info()
        return df[df[id] == self.id].email[0]

def get_all_info():
    # ...
我的想法是模拟Employee类,然后调用set_email方法来测试它。测试代码:

def test_set_email(get_all_info_mock):
    # ...
    mock_object = unittest.mock.Mock(Employee)

    actual_email = Employee.set_email(mock_object)

    assert actual_email == expected_email
运行测试时,我得到以下错误

AttributeError:模拟对象没有属性“id”

我试着按照这里的指示去做:。
我还尝试将mock设置为属性mock,id有副作用,id有返回值,但我似乎无法理解。我不想修补Employee类,因为目标是测试它的方法。

您需要做的就是设置
id
属性

def test_set_email(get_all_info_mock):
    # ...
    mock_object = unittest.mock.Mock(id=3)  # Or whatever id you need

    actual_email = Employee.set_email(mock_object)

    assert actual_email == expected_email

尝试
mock\u object=unittest.mock.mock(Employee,autospec=True)
我得到了相同的错误。在调试模拟对象时,如果没有
autospec=True
,模拟对象将如下所示
不要模拟类;这就是你正在测试的。模拟
获取所有信息
并创建
员工
@chepner我正在测试
设置电子邮件
的真实实例。如果我创建employee类的实例,它将调用
\uuuu init\uuuu
中的所有方法,这正是我试图避免的。为什么?如果您模拟
get_all_info
以返回静态数据帧(而不是查询某些外部资源,调用
set_email
没有问题)。这就是我要找的!我一直在创建一个单独的虚拟类,但这更好!感谢您在评论中与我打交道!