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

Photo by Chris Ried on Unsplash
user = UserController()
print("---")
print(user.get_first_picture())
print("---")
print(user.get_second_picture())
__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
Pic1
---
get_second_picture() method called
get_pictures_via_method() method called
get_DB() method called
all() method called
Pic2
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'>
mock.get_DB().all().__getitem__()

--

--

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