Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a return value which is an object

I'd like to write some tests for the following code:

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

How can I mock out get_person(id) method so that it returns an object which has a value for first_name property?

In code:

@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)
like image 245
zoran119 Avatar asked May 22 '17 12:05

zoran119


Video Answer


2 Answers

I think you should need to do something like this

class MockPerson(object):
    first_name = 'Bob'


@patch('get_person')
def test_person_name_length(self, get_person_mock):
    get_person_mock.return_value = MockPerson()
    self.assertEqual(person_name_length(1), 3)
like image 188
Maninder Singh Avatar answered Oct 17 '22 13:10

Maninder Singh


You don't need to create a one-off object for this. This is easier:

@patch('get_person')
def test_person_name_length(self, get_person_mock):
    get_person_mock.return_value = mock.Mock(first_name='Bob')
    self.assertEqual(person_name_length(1), 3)
like image 20
gaefan Avatar answered Oct 17 '22 14:10

gaefan