导入测试类执行测试用例
# 导入测试类执行测试用例 import unittest from folder_name.py_module_name import TestClass1, TestClass2 # ffolder_name import py_module_name # 为了运行模块中多个测试类 import HTMLTestRunner # ------------------------------ # 方法1 只执行部分用例 # suite = unittest.TestSuite() # 存储用例 # suite.addTest(TestClass1("test_method1")) # suite.addTest(TestClass1("test_method2")) # 添加一个用例,传入的参数是函数名 # # # # 执行存储的两个用例 # runner = unittest.TextTestRunner() # runner.run(suite) # ----------------------------------------------- # 方法2,TestLoader 按照从上到下的顺序执行测试类中的所有用例 # loader = unittest.TestLoader() # 加载用例 # suite = unittest.TestSuite() # 存储用例 # suite.addTest(loader.loadTestsFromTestCase(TestClass1)) # 传入测试类名,会自动找到这个类下所有的测试用例 # # runner = unittest.TextTestRunner() # runner.run(suite) # -------------------------------------------------- # 方法3,模块中定义了多个测试类,导入和传参的时候具体到模块名,不用写类名 from folder_name import py_module_name # loader = unittest.TestLoader() # suite = unittest.TestSuite() # suite.addTest(loader.loadTestsFromModule(py_module_name)) # # runner = unittest.TextTestRunner() # runner.run(suite) # ------------------------------------------------------------ # 把测试结果输出到文件中 # 加载用例 # loader = unittest.TestLoader() # suite = unittest.TestSuite() # suite.addTest(loader.loadTestsFromModule(py_module_name)) # 执行用例,把测试结果输出到文件中 # with open("test.text", "w+", encoding="utf-8") as file: # runner = unittest.TextTestRunner(verbosity=2) # runner.run(suite) # print(file.closed) # 判断文件是否关闭状态 # -------------------------------------------------------- suite = unittest.TestSuite() suite.addTest(TestClass1("test_method1")) suite.addTest(TestClass1("test_method2")) suite.addTest(TestClass1("test_method3")) test_case = [TestClass2("test_method1"), TestClass2("test_method2"), TestClass2("test_method3")] suite.addTests(test_case) with open("result.html", "wb") as file: runner = HTMLTestRunner.HTMLTestRunner(stream=file, title="单元测试报告", description="未来测试大佬") runner.run(suite)