之前介绍了环境搭建和requests库的使用,可以使用这些进行接口请求的发送。但是如何管理接口案例?返回结果如何自动校验?
从本节开始我们引入python单元测试框架 unittest,用它来处理批量用例管理,校验返回结果,初始化工作以及测试完成后的环境复原工作等等。
一、单个用例管理起来比较简单,参考如下图,单个用例一般多用在调试的时候:

二、代码如下:
# -*- coding:utf-8 -*-
import unittest
class TestOne(unittest.TestCase):
def setUp(self):
print '\ncases before'
pass
def test_add(self):
'''test add method'''
print 'add...'
a = 3 + 4
b = 7
self.assertEqual(a, b)
def test_sub(self):
'''test sub method'''
print 'sub...'
a = 10 - 5
b = 4
self.assertEqual(a, b)
def tearDown(self):
print 'case after'
pass
if __name__ == '__main__':
unittest.main()
输出结果:
Ran 2 tests in 0.001s
OK
cases before
add...
case after
cases before
sub...
case after
Process finished with exit code 0