unittest不同方法添加case
# 方法1、执行当前文件下的所有method:unittest.main()
# 方法2、添加单个method:TestSuite.addTest(className("methodName"))执行case
# 方法3、添加多个method:TestSuite.addTests(List)执行case
# list = [UserCase("test3_plus"),UserCase("test2_plus")]
# 方法4、批量添加多个文件的case:defaultTestLoader.discover(path, pattern='test*.py')
# 返回值为test suite
# 方法5、添加单个class下的所有method:TestLoader().loadTestsFromTestCase(className)
# 返回值为test suite
import unittest class UserCase1(unittest.TestCase): # def setUp(self): # print("setUp") # def tearDown(self): # print("tearDown") @classmethod def setUpClass(cls): print("setUpClass") @classmethod def tearDownClass(cls): print("tearDownClass") def test1_plus(self): a = 1+1 print(f"1+1={a}") self.assertEqual(a,2) def test2_plus(self): a = 1+2 print(f"1+2={a}") self.assertEqual(a,3) def test3_plus(self): a = 1+3 print(f"1+3={a}") self.assertEqual(a,4) @unittest.skip def test4_plus(self): a = 1+4 print(f"1+4={a}") self.assertEqual(a,5) class UserCase2(unittest.TestCase): # def setUp(self): # print("setUp") # def tearDown(self): # print("tearDown") @classmethod def setUpClass(cls): print("setUpClass-UserCase2") @classmethod def tearDownClass(cls): print("tearDownClass-UserCase2") def test1_plus(self): a = 1+1 print(f"1+1={a},UserCase2") self.assertEqual(a,2) def test2_plus(self): a = 1+2 print(f"1+2={a},UserCase2") self.assertEqual(a,3) def test3_plus(self): a = 1+3 print(f"1+3={a},UserCase2") self.assertEqual(a,4) @unittest.skip def test4_plus(self): a = 1+4 print(f"1+4={a},UserCase2") self.assertEqual(a,5) if __name__ == "__main__": # 方法1、执行当前文件下的所有method:unittest.main() # unittest.main() ''' # 方法2、添加单个method:TestSuite.addTest(className("methodName"))执行case suite = unittest.TestSuite() suite.addTest(UserCase1("test3_plus")) runner = unittest.TextTestRunner() runner.run(suite) ''' ''' # 方法3、添加多个method:TestSuite.addTests(List)执行case # 格式:addTests(list) suite = unittest.TestSuite() case = [UserCase1("test3_plus"),UserCase1("test2_plus")] suite.addTests(case) runner = unittest.TextTestRunner() runner.run(suite) ''' ''' # 方法4、批量添加多个文件的case:defaultTestLoader.discover(path, pattern='test*.py') # 返回值为test suite # pattern='test*.py' 规定测试集文件开头命名为test,也可以是pattern='test_*.py' # discover方法找到path 目录下所有文件到的测试用例组装到测试套件 # 因此可以直接通过run()方法执行discove path = './unittest/' suite = unittest.defaultTestLoader.discover(path, pattern='test*.py') # 或 suite = unittest.TestLoader().discover(path, pattern='test*.py') runner = unittest.TextTestRunner() runner.run(suite) ''' # 方法5、添加单个class下的所有method:TestLoader().loadTestsFromTestCase(className) # 返回值为test suite suite1 = unittest.TestLoader().loadTestsFromTestCase(UserCase1) suite2 = unittest.TestLoader().loadTestsFromTestCase(UserCase2) suite3 = unittest.TestSuite() suite3.addTests([suite1,suite2]) runner = unittest.TextTestRunner() # suite2 = unittest.TestSuite() # suite2.addTest(suite1) runner.run(suite3) # 解释:TestLoader 与 defaultTestLoader区别 # defaultTestLoader = TestLoader()