模拟作为对象的返回值

时间:2017-05-22 12:20:36

标签: python unit-testing mocking python-unittest

我想为以下代码编写一些测试:

def person_name_length(id):
    person = get_person(id)
    return len(person.first_name)

如何模拟get_person(id)方法,使其返回一个具有first_name属性值的对象?

在代码中:

@patch('get_person')
def test_person_name_length(self, get_person_mock):
    get_person_mock.return_value = # what goes here??? calling .first_name on it should return 'Bob'
    self.assertEqual(person_name_length(1), 3)

1 个答案:

答案 0 :(得分:1)

我认为你应该做这样的事情

class MockPersion(object):
    first_name = 'Bob'


@patch('get_person')
def test_person_name_length(self, get_person_mock):
    get_person_mock.return_value = MockPersion()
    self.assertEqual(person_name_length(1), 3)