import unittest # 用猴子补丁的方式解决 testcase 按定义的顺序执行用例 from unittest.loader import TestLoader # 自定义一个getTestCaseNames方法, 替换TestLoader中的getTestCaseNames方法 def getTestCaseNames(self, testCaseClass): def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname)) testFnNames = [] for testFnName in testCaseClass.__dict__: if isTestMethod(testFnName): testFnNames.append(testFnName) return testFnNames # 替换TestLoader中的getTestCaseNames方法 TestLoader.getTestCaseNames = getTestCaseNames
测试代码
class Test(unittest.TestCase): def setUp(self) -> None: print('setup') def test_b(self): print('test_b') def test_02(self): print('test-02') def test_01(self): print('test-01') def test_a(self): print('test-a') def meth(self): print('meth') if __name__ == '__main__': unittest.main()