记录一下Unittest的测试执行相关的点
一、测试用例执行的几种方式
1、通过unittest.main()来执行测试用例的方式:
if __name__ == "__main__": unittest.main()
2、通过testsuit来执行测试用例的方式:
if __name__=='__main__': case = ['TestCase'] suite = unittest.TestSuite(map(TestClassName,case)) unittest.TextTestRunner.run(suite)
3、通过testLoader方式:
if __name__ == "__main__": suite1 = unittest.TestLoader().loadTestsFromTestCase(TestCase1) suite2 = unittest.TestLoader().loadTestsFromTestCase(TestCase2) suite = unittest.TestSuite([suite1, suite2]) unittest.TextTestRunner(verbosity=2).run(suite)
4、通过defaultTestLoader.discover方式:
if __name__ == "__main__": #批量执行用例 #定义测试集所在文件夹 path = os.path.dirname(__file__)#当前执行路径 discover = unittest.defaultTestLoader.discover(path, pattern='test*.py') runner=unittest.TextTestRunner() runner.run(discover)
总结:个人推荐2、4这两种方式
二、跳过测试和设置预期失败
① @unittest.skip("reason") ==>直接跳过测试
@unittest.skip("skip TestCase") class TestCase(self):
② @unittest.skipIf(condition,"reason") ==>条件为真,跳过测试
class Test2(self): def test_c(self): @unittest.skipIf(1,"skip test_b") def test_b(self):
③ @unittest.skipUnless(condition,"reason") ==>条件为假,跳过测试
class Test(self): @unittest.skipUnless(0>2,"skip test") def test(self):
④ @unittest.expectedFailure ==>设置预期为失败
class Test1(self): @unittest.expectedFailure def test(self):
后面有相关的内容再持续更新吧