You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django REST API单元测试中测试500错误码?

测试Django REST Framework API的500内部错误码

要测试API的500错误,有两种简洁可靠的实现方式:

1. Mock核心业务逻辑抛出异常

直接Mock视图中依赖的核心函数/方法,让它抛出未捕获的异常,从而触发服务器500错误。比如如果你的用户详情视图依赖User.objects.get()这类方法,就可以用unittest.mock.patch模拟它抛出异常:

from unittest.mock import patch
from django.http import status
from rest_framework.test import APIClient, TestCase

class UserApiTests(TestCase):
    def setUp(self):
        self.client = APIClient()

    @patch('django.contrib.auth.models.User.objects.get')
    def test_retrieve_user_500_error(self, mock_get):
        """测试获取用户信息时触发服务器错误"""
        # 模拟核心方法抛出异常
        mock_get.side_effect = Exception("数据库查询失败")
        
        res = self.client.get(USER_URL)
        self.assertEqual(res.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)

2. 关闭DEBUG模式确保返回标准500响应

Django在DEBUG=True时,500错误会返回带调试信息的HTML页面,而非DRF的标准JSON响应。你可以用override_settings装饰器临时关闭DEBUG,确保测试能拿到正确的500状态码:

from django.test import override_settings
from django.http import status
from rest_framework.test import APIClient, TestCase

class UserApiTests(TestCase):
    def setUp(self):
        self.client = APIClient()

    @override_settings(DEBUG=False)
    def test_retrieve_user_500_error(self):
        """测试获取用户信息时触发服务器错误"""
        # 结合Mock触发异常
        with patch('your_app.views.get_user_profile') as mock_profile:
            mock_profile.side_effect = Exception("内部服务错误")
            
            res = self.client.get(USER_URL)
            self.assertEqual(res.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)

注意:两种方法结合使用效果最佳——Mock触发异常,同时关闭DEBUG确保响应格式符合API预期。

内容的提问来源于stack exchange,提问作者Incognito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:52:47