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

在 Django 框架中执行单元测试,主要依赖自带的 unittest 模块或支持的第三方库(如 pytest)。Django 提供了完整的测试运行机制,能自动发现并执行测试用例。
Django 的测试通常写在每个应用的 tests.py 文件中,也可以拆分为 tests/ 目录包含多个测试文件(如 test_models.py、test_views.py)。
示例:在 myapp/tests.py 中编写一个简单测试:
立即学习“Python免费学习笔记(深入)”;
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")
在项目根目录下(manage.py 所在目录),使用以下命令运行测试:
python manage.py test
这条命令会:
你也可以指定运行某个应用、模块甚至具体测试方法:
# 只测试某个应用 python manage.py test myapp <h1>测试某个测试文件中的类</h1><p>python manage.py test myapp.tests.MyModelTest</p><h1>测试具体的测试方法</h1><p>python manage.py test myapp.tests.MyModelTest.test_model_creation
Django 支持多种测试参数来控制执行行为:
--verbosity:设置输出详细程度(0、1、2)--keepdb:保留测试数据库,加快下次测试启动--failfast:遇到第一个失败时停止执行--parallel:并行运行测试(Django 2.0+)例如:
python manage.py test --keepdb --verbosity=2
确保测试环境干净、独立:
TestCase 类可自动管理事务回滚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怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号