如何进行Django单元测试?

本文介绍了如何在Django中进行单元测试,使用python的unittest模块创建基于类的测试用例。通过`python manage.py test`等命令,可以执行单个测试文件、特定测试类或方法,以及设置测试参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Django的单元测试使用python的unittest模块,这个模块使用基于类的方法来定义测试。类名为django.test.TestCase,继承于python的unittest.TestCase。

from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):
    def setUp(self):
        Animal.objects.create(name="lion", sound="roar")
        Animal.objects.create(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        lion = Animal.objects.get(name="lion")
        cat = Animal.objects.get(name="cat")
        self.assertEqual(lion.speak(), 'The lion says "roar"')
        self.assertEqual(cat.speak(), 'The cat says "meow"')

执行目录下所有的测试(所有的test*.py文件):运行测试的时候,测试程序会在所有以test开头的文件中查找所有的test cases(inittest.TestCase的子类),自动建立测试集然后运行测试。

1 $ python manage.py test

执行animals项目下tests包里的测试:

1 $ python manage.py testanimals.tests

执行animals项目里的test测试:

1 $ python manage.py testanimals

单独执行某个test case:

1 $ python manage.py testanimals.tests.AnimalTestCase

单独执行某个测试方法:

1 $ python manage.py testanimals.tests.AnimalTestCase.test_animals_can_speak

为测试文件提供路径:

1 $ python manage.py testanimals/

通配测试文件名:

1 $ python manage.py test–pattern=”tests_*.py”

启用warnings提醒:

1 $ python -Wall manage.py test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豆豆orz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值