Django unittest 单元测试

时间:2022-08-07 14:49:16

这里就不再介绍单元测试的作用了。

首先单元测试的创建方式有两种,一种是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 !!!')

调用

Django unittest 单元测试

也可以这样调用

python3 manage.py test app01.tests

直接test会进行全局查找,而上面的命令是对于各个子测试的执行

方法二、自定义文件

如下格式创建文件目录

Django unittest 单元测试

 # -*- coding: utf-8 -*-
# __author__ = 'dandy' from django.test import TestCase
from rest_framework.test import APIRequestFactory class TestOrderAPI(TestCase): def setUp(self):
self.factory = APIRequestFactory() def test_name(self):
"""
测试创建订单 :return:
"""
print('testing name ...........')
name = 'dandy'
self.assertEqual(name, 'dandy')
print('test name success !!!') def test_age(self):
"""
测试创建订单 :return:
"""
print('testing age ...........')
age = 18
self.assertEqual(age, 17)
print('test age success !!!')

执行

Django unittest 单元测试

此时如果执行test命令

Django unittest 单元测试

 from django.test import TestCase
from rest_framework.test import APIRequestFactory
from api.test.util.mock_data import data_create_order
from api import views
from backend.models import User
from backend.constant import Constant class TestOrderAPI(TestCase):
"""
订单接口测试用例
""" def setUp(self):
self.factory = APIRequestFactory() def test_create(self):
"""
测试创建订单 :return:
"""
request = self.factory.post('/order/', data_create_order, format='json')
response = views.OrderCreateView.as_view()(request)
self.assertEqual(response.data['code'], 20000) def test_order_detail(self):
"""
获取订单详情 :return:
"""
request = self.factory.post('/order/', data_create_order, format='json')
response = views.OrderCreateView.as_view()(request) order_no = response.data['data']['order_no']
url = '/order/%(number)s/' % {'number': order_no}
request = self.factory.get(url)
response = views.OrderDetailView.as_view()(request, number=order_no)
self.assertEqual(response.data['code'], 20000)

实战

更多基础知识

https://www.jianshu.com/p/34267dd79ad6

https://docs.djangoproject.com/en/2.1/topics/testing/