1、命名规则
以test_开头
1 impot unittest 2 3 class Cs(unittest.TestClass): 4 def test_01(self): 5 pass
2、装饰器:
@classmethod 只执行一次
@unitest.skip(
无条件跳过执行测试,reason
)描述为什么跳过测试
@unittest.skipif(
conditition
,reason
) conditition是true时跳过测试
@unittest.skipunless(condition,reason)
condition
不是true时跳过测试
@expected failure 使用@
unittest.expectedFailure
装饰器,如果test失败了,不计入失败的case里面
1 import unittest 2 3 4 class TsetCase(unittest.TestCase): 5 # 执行用例前 6 @classmethod 7 def tearDownClass(cls): 8 print('测试结束了!!') 9 10 @classmethod 11 def setUpClass(cls): 12 print('开始测试了!!') 13 14 @unittest.skip('不需要执行这条测试用例') 15 def test_01(self): 16 a = 1 17 b = 2 18 self.assertEqual(a + b, 3) 19 20 if __name__ == '__main__': 21 unittest.main()
参考来源:https://www.jianshu.com/p/ba5dbcb5d71b
3‘、固定套件:
unittest module
包含了编写运行unittest
的功能,自定义的test class
都要集成
unitest.TestCase
类,test method
要以test
开头,运行顺序根据名字排序,特殊方法:
①tearDownClass(cls) 执行测试前函数
②setUpClass(cls) 执行用例后函授
③setUp(self) 每次执行测试都要执行一次
④tearDown(self) 每次执行测试完成后执行一次
运行测试方法:
unittest.main() 执行所有的case
unittest.TestSuite() 测试套件
runner = unittest.TextTestRunner() 实例化TextTestRunner类
import unittest class TsetCase(unittest.TestCase): # 执行用例前 @classmethod def tearDownClass(cls): print('测试结束了!!') @classmethod def setUpClass(cls): print('开始测试了!!') def setUp(self): print('开始执行') def tearDown(self): print('执行完成') @unittest.skip('不需要执行这条测试用例') def test_01(self): a = 1 b = 2 self.assertEqual(a + b, 3) def test_02(self): a = 2 b = 3 self.assertEqual(a+b,4) if __name__ == '__main__': # unittest.main() # suite = unittest.TestSuite() # suite.addTest(TsetCase('test_01')) # runner = unittest.TextTestRunner() # runner.run(suite) ljwj = r'F:\项目\京东登陆\TestCases' cszx = unittest.defaultTestLoader.discover(start_dir=ljwj , pattern='test_*.py') runner = unittest.TextTestRunner() runner.run(cszx)