单元测试

it2023-09-07  68

认识单元测试

单元测试:测类,方法,函数,测试最小单位由于django的特殊性,通过接口测单元,代码逻辑都放在类视图中单元测试好处 消灭低级错误快速定位bug(有些分支走不到,通过单元测试提前测出问题)提高代码质量(测试后顺便优化代码)

编写和运行django的单元测试

django环境

数据库编码数据库用户权限(需要建临时数据库、删临时数据库)

每个应用,自带tests.py

类,继承django.test.TestCase前置、后置方法test开头的测试用例

集成在django的项目文件里,更多是开发人员写django自动的测试

运行

进入manage.py目录命令 python manage.py test 指定目录下的某个文件

TestCase类

前后置方法运行特点 django.test.TestCase类主要由前、后置处理方法 和test开头的方法组成

test开头的方法 是编写了测试逻辑的用例setUp方法 (名字固定)在每一个测试方法执行之前被调用tearDown方法(名字固定) 在每一个测试方法执行之前被调用setUpClass类方法(名字固定)在整个类运行前执行只执行一次tearDownClass类方法(名字固定)在调用整个类测试方法后执行一次 from django.test import TestCase class MyTest(TestCase): @classmethod def setUpClass(cls): print('setUpClass') @classmethod def tearDownClass(cls): print('tearDownClass') def setUp(self) -> None: print('setUp') def tearDown(self) -> None: print('tearDown') def test_xxx(self): print('测试用例1') def test_yyy(self): print('测试用例2') # python manage.py test meiduo_mall.apps.users.test_code

setUpClass 和 tearDownClass应用场景

写测试代码:放在test开头的方法

# 定义 setUpClass: 用户登录 # 定义 tearDownClass: 用户退出 # 定义测试方法:获取用户信息、获取用户浏览器记录、获取用户地址列表 from django.test import TestCase import requests class MyTest(TestCase): s = None # 类属性 @classmethod def setUpClass(cls): print('setUpClass') user_info = { "username": "mike123", "password": "chuanzhi12345", "remembered": True } # 1. 创建requests.Session()对象 # cls.s类属性的s对象 cls.s = requests.Session() # 登陆 # json以json格式发送请求 r = cls.s.post('http://127.0.0.1:8000/login/', json=user_info) print('登陆结果=', r.json()) @classmethod def tearDownClass(cls): print('tearDownClass') r = cls.s.delete('http://127.0.0.1:8000/logout/') print('登出结果=', r.json()) def test_1_info(self): r = self.s.get('http://127.0.0.1:8000/info/') print('用户结果=', r.json()) def test_2_browse_histories(self): r = self.s.get('http://127.0.0.1:8000/browse_histories/') print('浏览记录结果=', r.json()) def test_2_browse_addresses(self): r = self.s.get('http://127.0.0.1:8000/addresses/') print('地址结果=', r.json())
最新回复(0)