unittest核心要素:
- TestCase:指一条测试用例,也就是一条完整的测试流程;包括测试前环境的准备(SetUp),执行测试代码,以及测试后环境的还原;单元测试(unit test)的本质也就在这里,一条测试用例是一个完整的测试单元,通过运行这个测试单元,可以对某一问题进行验证;
- TestSuite:多个测试用例集合在一起,就是TestSuite;而且TestSuite可以嵌套多个TestSuite;TestLoader是用来加载测试用例到TestSuite的
- TextTestRunner:是用来执行测试用例的,其中的run会执行TestSuite/TestCase中的Run方法;测试的结果会保存到TextTestResult实例中,包括运行了多少测试用例,成功了多少,失败了多少等信息;
- Fixture:对一个测试用例环境的搭建和销毁,是一个fixture;
1.常用断言方法
使用方法 | 说明 | assertEqual(a, b) | 判断a == b | assertNotEqual(a, b) | 判断a != b | assertTrue(x) | 判断bool(x) is True | assertFalse(x) | 判断bool(x) is False | assertIs(a ,b) | a is b | assertIsNot(a, b) | a is not b | assertIsNone(x) | x is None | assertIsNotNone(x) | x is not None | assertIn(a, b) | a in b | assertNotIn(a, b) | a not in b | assertIsInstance(a, b) | instance(a, b) | assertNotIsInstance(a, b) | not?instance(a, b) |
2.用例执行顺序
测试类或测试方法的数字与字母顺序:0~9、a~z
3.TestSuite
1.使用addTest/addTests添加用例到suite
# addTest方法
suite = unittest.TestSuite() # 构建测试集
suite.addTest(Test1('test_d'))
runner = unittest.TextTestRunner() # 构建runner
runner.run(suite)
# addTests方法
suite = unittest.TestSuite()
suite.addTests((Test1('test_d'), Test1('test_a'))) # 传入testcase元组
runner = unittest.TextTestRunner()
runner.run(suite)
2.discover
test_dir = './'
discovery = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
runner = unittest.TextTestRunner()
runner.run(discovery)
3.TestLoader
suite = unittest.TestSuite()
# suite.addTests(unittest.TestLoader().loadTestsFromName('test_add.Test1')) # loadTestsFromName('模块名.类名'))
suite.addTests(unittest.TestLoader().loadTestsFromNames(['test_add.Test1', 'test_add.Test2'])) # loadTestsFromNames(['模块名.类名', '模块名.类名']))
runner = unittest.TextTestRunner()
runner.run(suite)
suite = unittest.TestSuite()
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(Test1)) # loadTestsFromTestCase(),传入TestCase
runner = unittest.TextTestRunner()
runner.run(suite)
注意:使用TestLoader无法对case进行排序的;同时,suite可以套suite
?4.TextTestResult
1.将结果输出到文件中
suite = unittest.TestSuite()
suite.addTest(Test1('test_d'))
with open ('report.txt', 'a') as f:
runner = unittest.TextTestRunner(stream=f, verbosity=2)
runner.run(suite)
跳过某些case
1.skip装饰器
|