Reputation: 337
I want to unit test this class method update
class EmployeeUpdateSerializer(serializers.ModelSerializer):
def update(self, instance, data):
shift_types = data.pop('shift_types', None)
instance = super().update(instance, data)
self.update_shift_type(instance, shift_types)
return instance
I am doing this
class TestEmployeeUpdateSerializer(TestCase):
def setUp(self):
self.company, self.user, self.header = create_user_session()
self.serializer = EmployeeUpdateSerializer()
def test_update(self):
employee = self.user
with patch.object(self.serializer, 'update') as update:
with patch.object(self.serializer, 'update_shift_type') as update_shift_type:
res = self.serializer.update(employee, dict())
update.assert_called_once_with(employee, dict())
update_shift_type.assert_called_once_with(employee, None)
self.assertEqual(res, employee)
But this gives me an error
Traceback (most recent call last):
File "/Users/shahzadfarukh/my-croft/backend/account/tests/test_employee_serializers.py", line 222, in test_update
update_shift_type.assert_called_once_with(employee, None)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 830, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'update_shift_type' to be called once. Called 0 times.
Please help me! is something I am doing wrong?
Upvotes: 0
Views: 914
Reputation: 16815
You have mocked update
, so its original code won't get called. If you want to test what update
calls, you have to call the original version, and mock only functions/methods called within the update. Assuming the base class is imported like import serializers
, you could do something like this (untested)
class TestEmployeeUpdateSerializer(TestCase):
def setUp(self):
self.company, self.user, self.header = create_user_session()
self.serializer = EmployeeUpdateSerializer()
@patch('serializers.ModelSerializer.update')
@patch('serializers.ModelSerializer.update_shift_type')
def test_update(self, mocked_update_shift_type, mocked_update):
employee = self.user
res = self.serializer.update(employee, dict())
mocked_update.assert_called_once_with(employee, dict())
mocked_update_shift_type.assert_called_once_with(employee, None)
self.assertEqual(res, employee)
Upvotes: 2