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. 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'
I tried to follow the directions here: Better way to mock class attribute in python unit test . 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. I don't want to patch the Employee class because the goal is to test it's methods.
All you need to do is set the id
attribute.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.