简体   繁体   English

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

[英]Testing class method that calls an instance variable - AttributeError

How can I mock a class to test its methods in isolation when they use instance variables? 当它们使用实例变量时,如何模拟一个类以隔离地测试其方法? This is an example of the code I am trying to test. 这是我要测试的代码示例。

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():
    # ...

My thought is to Mock the Employee class then call the set_email method to test it. 我的想法是模拟Employee类,然后调用set_email方法进行测试。 The testing code: 测试代码:

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

When running the test I get the following error. 运行测试时,出现以下错误。

AttributeError: Mock object has no attribute 'id' AttributeError:模拟对象没有属性“ id”

I tried to follow the directions here: Better way to mock class attribute in python unit test . 我尝试遵循以下指示: 在python单元测试中模拟类属性的更好方法 I've also tried to set the mock as a property mock, id witha side_effect, and id with a return_value but I can't seem to figure it out. 我还尝试将模拟设置为属性模拟,id为side_effect,id为return_value,但我似乎无法弄清楚。 I don't want to patch the Employee class because the goal is to test it's methods. 我不想修补Employee类,因为目标是测试它的方法。

All you need to do is set the id attribute. 您需要做的就是设置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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM