Testing Django Try - Except View function

it’s probably a straightforward simple problem but i haven’t found similar information. I want to test a get function, which throws a generic exception, in case any event if the model fails. This is my view:

@api_view(['GET'])
def get_group(request):
    """
    Returns all works
    """
    try:
        group = Group.objects.all()
        serializer = GroupSerializer(group, many=True)
        return Response(serializer.data)
    except Exception as e:
        return Response(data={'error': e.args}, status=500)

I have the test that does not throw an exception, but I need it to cover the one that throws an exception and I can’t find a way. I have tried several things but the closest thing to get right has been this, but always returns status = 200.

@patch('api.serializers.GroupSerializer')
def test_get_group_list_fail(self, MockSerializer):
    MockSerializer.side_effect = Exception()
    response = self.client.get('/groups/')

Thank you

Hi RafaMn, if you have your serializers defined in a serializers.py module, then the solution should be changing the patch to define the path to target the views.py module (assuming that’s where your view is defined).

@patch('api.views.GroupSerializer')  # changed from api.serializers.GroupSerializer
def test_get_group_list_fail(self, MockSerializer):