Unit Tests Return MagicMock Object Instead of return_value. How to Fix This?

Photo by Chris Ried on Unsplash
user = UserController()
__init__ method in the UserController class called
__init__ method in the Picture class called
get_first_picture() method called
get_pictures_via_variable() method called
all() method called
get_second_picture() method called
get_pictures_via_method() method called
get_DB() method called
all() method called
AssertionError: 'Test 1' != <MagicMock name='mock.dbal.all().__getitem__()' id='4456571856'>
return self.picture.dbal.all()
mock_app.dbal.all.return_value = ["Test 1", "Test 2"]

A unit test for the get_second_picture method

Let’s copy/paste the unit test for get_second_picture. Because these two methods are very, very similar, right?

AssertionError: 'Test 2' != <MagicMock name='mock.get_DB().all().__getitem__()' id='4387991856'>
return self.picture.get_DB().all()
AssertionError: 'Test 2' != <MagicMock name='mock.get_DB().all().__getitem__()' id='4459012640'>



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store