摘自:unittest官方文档
unittest中的重要概念
1、test fixture
test fixture做的是执行测试用例之前的准备工作,包括建立什么连接,断开连接等等准备工作
2、test case
test case是一个独立的测试单元,验证针对某一个输入的输出是否正确,unittest提供一个类TestCase,这个类被用来新建新的测试用例
3、test suite
test suite是testcase或者testsuite的集合,被用来集合所有的等待执行的测试用例
4、test runner
test runner是一个执行测试的组件,并且返回执行的测试结果
Basic example
一个testcase是通过继承unittest.TestCase来创建测试用例,每个测试方法都要以test开头,这样才能识别哪些方法是要被运行的测试方法。通过unittest提供的断言方法assertEqual()来判定要测试的结果跟预期结果是不是一样,用assertTrue()和assertFalse()来验证待测试条件正确与否,使用这些断言方法可以让test runner收集测试结果产生测试报告并输出。各种断言方法详见:unittest的TestCase类提供的判断方法
其中还有setUp()和tearDown()方法可以执行在测试方法运行之前的准备工作和测试方法完成之后的清理工作。
unittest.main()是运行用例的入口
demo:
import unittest
class TestStringMethods(unittest.TestCase):
def setUp(self):
print("这是准备!")
def test_upper(self):
print("test_upper准备完成")
self.assertEqual('foo'.upper(), 'FOO')
print("test_upper执行完成")
def test_isupper(self):
print("test_isupper准备完成")
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
print("test_isupper执行完成")
def test_split(self):
print("test_split准备完成")
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
print("test_split执行完成")
def tearDown(self):
print("这是结束")
if __name__ == '__main__':
unittest.main()
输出结果:
这是准备!
test_isupper准备完成
test_isupper执行完成
这是结束
这是准备!
test_split准备完成
test_split执行完成
这是结束
这是准备!
test_upper准备完成
test_upper执行完成
这是结束
...
----------------------------------------------------------------------
Ran 3 tests in 0.006s
OK
所以可以看出每次执行test开头的测试方法的时候,总是会先运行setup()和teardown()方法,所以想实现不停的setup和teardown的时候可以使用unittest的TestSuite类,这个类用来把所有的testcase集合在一起组成一个testsuite。
使用:首先建立TestSuite类的实例,然后通过addTest()方法把testcase组合到一起
def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase('test_default_widget_size'))
suite.addTest(WidgetTestCase('test_widget_resize'))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite())