Django 中执行单元测试主要依赖自带的 unittest 模块,通过 TestCase 编写测试用例并使用 python manage.py test 运行,支持指定应用、类或方法级别测试,可利用 --keepdb、--parallel 等参数优化执行,测试中使用 Client 模拟请求,所有测试在隔离的数据库中运行以保证环境干净。

在 Django 框架中执行单元测试,主要依赖自带的 unittest 模块或支持的第三方库(如 pytest)。Django 提供了完整的测试运行机制,能自动发现并执行测试用例。
1. 编写测试用例
Django 的测试通常写在每个应用的 tests.py 文件中,也可以拆分为 tests/ 目录包含多个测试文件(如 test_models.py、test_views.py)。
示例:在 myapp/tests.py 中编写一个简单测试:
from django.test import TestCase from myapp.models import MyModel <p>class MyModelTest(TestCase): def test_model_creation(self): obj = MyModel.objects.create(name="Test") self.assertEqual(obj.name, "Test") </p>
2. 运行测试命令
在项目根目录下(manage.py 所在目录),使用以下命令运行测试:
python manage.py test
这条命令会:
- 查找所有已安装应用中的测试
- 创建专用的测试数据库
- 运行测试用例
- 输出结果并自动销毁测试数据库
你也可以指定运行某个应用、模块甚至具体测试方法:
# 只测试某个应用 python manage.py test myapp <h1>测试某个测试文件中的类</h1><p>python manage.py test myapp.tests.MyModelTest</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation"><img src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Camoufox Open Source Anti-Detect Browser for Python Automation" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation" class="overflowclass">Camoufox Open Source Anti-Detect Browser for Python Automation</a> <p class="overflowclass">Camoufox 是一个基于 Firefox 构建的开源反检测浏览器,为 Python 自动化工作流程提供强大的指纹注入和反机器人检测规避功能。它与 Playwright 集成,以提供能够绕过现代机器人检测系统的隐身浏览能力。</p> </div> <a rel="nofollow" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div><h1>测试具体的测试方法</h1><p>python manage.py test myapp.tests.MyModelTest.test_model_creation </p>
3. 使用测试配置和选项
Django 支持多种测试参数来控制执行行为:
-
--verbosity:设置输出详细程度(0、1、2) -
--keepdb:保留测试数据库,加快下次测试启动 -
--failfast:遇到第一个失败时停止执行 -
--parallel:并行运行测试(Django 2.0+)
例如:
python manage.py test --keepdb --verbosity=2
4. 测试注意事项
确保测试环境干净、独立:
- 测试数据不会影响开发或生产数据库
- 每个测试方法应相互隔离
- 使用
TestCase类可自动管理事务回滚 - 对于需要真实 HTTP 请求的视图测试,可用
Client或APIClient(DRF)
示例使用 Client 测试视图:
from django.test import TestCase, Client
<p>class MyViewTest(TestCase):
def setUp(self):
self.client = Client()</p><pre class="brush:python;toolbar:false;">def test_home_page(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
基本上就这些。只要写好测试用例,用 python manage.py test 启动即可,Django 会处理底层细节。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










