后端举例,接口测试在实际应用中编写最容易,编写速度最快的就是整合测试。
1)整合测试测试接口逻辑与数据库ORM等多个功能,可以用到web开发框架(如Django、Flask等)自带的测试客户端和测试类(如Django的TestCase)。
2)不管是接口测试用例还是单元测试用例,其主要测试方向都是集中测试指定的接口或函数功能上”做什么”。如,对于REST型接口而言,主要测试的方面包括:传入有效和无效参数、接口返回的预期的状态码、返回与前端约定的数据格式,数据库数据异常情况下的接口数据处理等。
代码举例如下
import json
from django.test import TestCase
from lists.models import List, Item
from lists.forms import DUPLICATE_ITEM_ERROR, EMPTY_ITEM_ERROR
class ListAPITest(TestCase):
base_url = "/api/lists/{}/"
def test_get_returns_json_200(self):
''' 测试get接口返回了200的json '''
list_ = List.objects.create()
response = self.client.get(self.base_url.format(list_.id))
self.assertEqual(response.status_code, 200)
self.assertEqual(response["content-type"], "application/json")
def test_get_returns_items_for_correct_list(self):
''' 测试api返回指定清单的所有待办事项 '''
other_list = List.objects.create()
Item.objects.create(list=other_list, text="待办事项1")
our_list = List.objects.create()
item1 = Item.objects.create(list=our_list, text="待办事项1")
item2 = Item.objects.create(list=our_list, text="待办事项2")
response = self.client.get(self.base_url.format(our_list.id))
self.assertEqual(
json.loads(response.content.decode("utf8"))