內容總括ide
一. 初始化測試
二. 執行順序ui
三. 斷言spa
四. 報告3d
五. 其餘code
解析
1. setUp 與 tearDownblog
2. setUpClass 與 tearDownClassip
class BaiDuTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("start...")
@classmethod
def tearDownClass(self):
print("end...")
if __name__ == '__main__':
unittest.main(verbosity=1)
3. unittest.main(verbosity=0/1/2)utf-8
4 .按順序執行 addTest資源
1 import unittest 2 3 class BaiDuTest(unittest.TestCase): 4 @classmethod 5 def setUpClass(cls): 6 print("start...") 7 8 @classmethod 9 def tearDownClass(self): 10 print("end...") 11 def test_baidu(self): 12 print("baidu...") 13 def test_souhu(self): 14 print("souhu...") 15 16 if __name__ == '__main__': 17 suit = unittest.TestSuite() 18 suit.addTest(BaiDuTest.test_souhu) 19 suit.addTest(BaiDuTest.test_baidu) 20 unittest.TextTestRunner(verbosity=2).run(suit)
5. 按測試類執行
1 import unittest 2 3 class BaiDuTest(unittest.TestCase): 4 @classmethod 5 def setUpClass(cls): 6 print("start...") 7 8 @classmethod 9 def tearDownClass(self): 10 print("end...") 11 def test_baidu(self): 12 print("baidu...") 13 def test_souhu(self): 14 print("souhu...") 15 16 class BaiDuTest2(unittest.TestCase): 17 @classmethod 18 def setUpClass(cls): 19 print("start2...") 20 21 @classmethod 22 def tearDownClass(self): 23 print("end2...") 24 def test_baidu(self): 25 print("baidu2...") 26 27 if __name__ == '__main__': 28 suit = unittest.TestSuite(unittest.makeSuite(BaiDuTest2)) 29 unittest.TextTestRunner(verbosity=2).run(suit) 30
suit = unittest.TestLoader().loadTestsFromTestCase(BaiDuTest2)
unittest.TextTestRunner(verbosity=2).run(suit)
6. 按測試模塊執行
1 # -*- coding:utf-8 -*- 2 import unittest 3 import os 4 5 class BaiDuTest(unittest.TestCase): 6 def test_baidu(self): 7 print("baidu...") 8 9 if __name__ == '__main__': 10 # 定義測試集所在文件夾 11 path = os.path.dirname(__file__) # 當前執行路徑 12 print(path) 13 # discover = unittest.defaultTestLoader.discover(path,pattern='test*.py') # 支持正則 14 discover = unittest.defaultTestLoader.discover(path,pattern='ttst.py') 15 runner = unittest.TextTestRunner(verbosity=2).run(discover)
7. 分離初始化模塊
1 class InitTest(unittest.TestCase): 2 @classmethod 3 def setUpClass(cls): 4 print("start...") 5 6 @classmethod 7 def tearDownClass(self): 8 print("end...") 9 10 class BaiDuTest(InitTest): 11 def test_baidu(self): 12 print("baidu...")
8. skip, skipIf
1 class BaiDuTest(InitTest): 2 def test_baidu(self): 3 print("baidu...") 4 5 @unittest.skip("skip TestCase") 6 def test_baidu2(self): 7 print("baidu2...") 8 9 @unittest.skipIf(1!=1,"skip TestCase") 10 def test_baidu3(self): 11 print("baidu3...") 12 13 14 15 if __name__ == '__main__': 16 unittest.main(verbosity=2)
9. 斷言
1 def test_baidu2(self): 2 self.assertEqual(1,'1') 3 self.assertTrue(0) 4 self.assertFalse(0) 5 self.assertIn('www','http://www.b')
⚠️ 第二行代碼錯了,就不會執行執行第3,4,5行代碼