Python中unittest测试根据不同参数组合产生单独的test case的解决办法
在某种情况下,需要用不同的参数组合测试同样的行为,你希望从test case的执行结果上知道在测试什么,而不是单单得到一个大的 test case;此时如果仅仅写一个test case并用内嵌循环来进行,那么其中一个除了错误,很难从测试结果里边看出来。
-
利用setattr来自动为已有的TestCase类添加成员函数
-
为了使这个方法凑效,需要用类的static method来生成decorate类的成员函数,并使该函数返回一个test函数对象出去
-
在某个地方注册这个添加test成员函数的调用(只需要在实际执行前就可以,可以放在模块中自动执行亦可以手动调用)
代码实例:
import unittest
from test import test_support
class MyTestCase(unittest.TestCase):
def setUp(self):
#some setup code
pass
def clear(self):
#some cleanup code
pass
def action(self, arg1, arg2):
pass
@staticmethod
def getTestFunc(arg1, arg2):
def func(self):
self.action(arg1, arg2)
return func
def __generateTestCases():
arglists = [('arg11', 'arg12'), ('arg21', 'arg22'), ('arg31', 'arg32')]
for args in arglists:
setattr(MyTestCase, 'test_func_%s_%s'%(args[0], args[1]),
MyTestCase.getTestFunc(*args) )
__generateTestCases()
if __name__ =='__main__':
#test_support.run_unittest(MyTestCase)
unittest.main()