以下是对 unittest.TestCase 类的扩展,使其支持参数化把参数加进去。下面是具体的代码实现过程:
- class ExtendTestCaseParams(unittest.TestCase):
- #扩展 unittest.TestCase 类,使其支持自定义参数输入
-
- def __init__(self, method_name='runTest', canshu=None):
-
- super(ExtendTestCaseParams, self).__init__(method_name)
-
- self.canshu = canshu
-
- #静态参数化方法
-
- @staticmethod
-
- def parametrize(testcase_klass, default_name=None, canshu=None):
-
- """ Create a suite containing all tests taken from the given
-
- subclass, passing them the parameter 'canshu'
-
- """
-
- test_loader = unittest.TestLoader()
-
- testcase_names = test_loader.getTestCaseNames(testcase_klass)
-
- suite = unittest.TestSuite()
-
- if default_name != None:
-
- for casename in testcase_names:
-
- if casename == defName:
-
- suite.addTest(testcase_klass(casename, canshu=canshu))
-
- else:
-
- for casename in testcase_names:
-
- suite.addTest(testcase_klass(casename, canshu=canshu))
-
- return suite
这里,canshu 就是优化后加的自定义参数,参数类型可以是元组或列表。下面使用这个参数化类来改写之前的代码。
- class ApiTestSample(ExtendTestCaseParams):
-
- def setUp(self):
-
- pass
-
- def tearDown(self):
-
- pass
-
- def jiafa(self, input01, input02):
-
- result = input01 + input02
-
- return result
-
- def test_jiafa(self):
-
- input_01 = self.param[0]
-
- input_02 = self.param[1]
-
- expectedResult = self.param[2]
-
- result = self.sub(input_01, input_02)
-
- print(result)
-
- self.assertEqual(result, expectedResult)
-
- if __name__=='__main__':
-
- testData = [
-
- (10, 9, 19),
-
- (12, 13, 25),
-
- (12, 10, 22),
-
- (2, 4, 6)
-
- ]
-
- suite = unittest.TestSuite()
-
- for i in testData:
-
- suite.addTest(ExtendTestCaseParams.parametrize(ApiTestSample, 'test_jiafa', canshu=i))
-
- runner = unittest.TextTestRunner()
-
- runner.run(suite)
(编辑:惠州站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|