这里就不再介绍单元测试的作用了。
首先单元测试的创建方式有两种,一种是app下面的test文件,另一种是自定义方式创建
方法一、使用test.py文件测试
from django.test import TestCase # Create your tests here. # -*- coding: utf-8 -*- # __author__ = 'dandy' from rest_framework.test import APIRequestFactory class TestOrderAPI(TestCase): def setUp(self): self.factory = APIRequestFactory() print('starting') def test_name1(self): """ 测试创建订单 :return: """ print('testing name111 ...........') name = 'dandy' self.assertEqual(name, 'dandy') print('test name success !!!') def test_age1(self): """ 测试创建订单 :return: """ print('testing age111 ...........') age = 18 self.assertEqual(age, 17) print('test age success !!!')
调用
也可以这样调用
python3 manage.py test app01.tests
直接test会进行全局查找,而上面的命令是对于各个子测试的执行
方法二、自定义文件
如下格式创建文件目录
1 # -*- coding: utf-8 -*- 2 # __author__ = 'dandy' 3 4 from django.test import TestCase 5 from rest_framework.test import APIRequestFactory 6 7 8 class TestOrderAPI(TestCase): 9 10 def setUp(self): 11 self.factory = APIRequestFactory() 12 13 14 def test_name(self): 15 """ 16 测试创建订单 17 18 :return: 19 """ 20 print('testing name ...........') 21 name = 'dandy' 22 self.assertEqual(name, 'dandy') 23 print('test name success !!!') 24 25 26 def test_age(self): 27 """ 28 测试创建订单 29 30 :return: 31 """ 32 print('testing age ...........') 33 age = 18 34 self.assertEqual(age, 17) 35 print('test age success !!!')
执行
此时如果执行test命令
1 from django.test import TestCase 2 from rest_framework.test import APIRequestFactory 3 from api.test.util.mock_data import data_create_order 4 from api import views 5 from backend.models import User 6 from backend.constant import Constant 7 8 class TestOrderAPI(TestCase): 9 """ 10 订单接口测试用例 11 """ 12 13 def setUp(self): 14 self.factory = APIRequestFactory() 15 16 def test_create(self): 17 """ 18 测试创建订单 19 20 :return: 21 """ 22 request = self.factory.post('/order/', data_create_order, format='json') 23 response = views.OrderCreateView.as_view()(request) 24 self.assertEqual(response.data['code'], 20000) 25 26 def test_order_detail(self): 27 """ 28 获取订单详情 29 30 :return: 31 """ 32 request = self.factory.post('/order/', data_create_order, format='json') 33 response = views.OrderCreateView.as_view()(request) 34 35 order_no = response.data['data']['order_no'] 36 url = '/order/%(number)s/' % {'number': order_no} 37 request = self.factory.get(url) 38 response = views.OrderDetailView.as_view()(request, number=order_no) 39 self.assertEqual(response.data['code'], 20000)
更多基础知识