Python主要讲究简洁简单使用,所以它不像junit一样支持参数化测试,需要改装一下也可以传参。直接上代码实例
- import unittest
- class ParametrizedTestCase(unittest.TestCase):
- """ TestCase classes that want to be parametrized should
- inherit from this class.
- """
- def __init__(self, methodName='runTest', param=None):
- super(ParametrizedTestCase, self).__init__(methodName)
- self.param = param
- @staticmethod
- def parametrize(testcase_klass, param=None):
- """ Create a suite containing all tests taken from the given
- subclass, passing them the parameter 'param'.
- """
- testloader = unittest.TestLoader()
- testnames = testloader.getTestCaseNames(testcase_klass)
- suite = unittest.TestSuite()
- for name in testnames:
- suite.addTest(testcase_klass(name, param=param))
- return suite
- #####################################################
- ##用法-testcase
- class TestOne(ParametrizedTestCase):
- def test_something(self):
- print 'param =', self.param
- self.assertEqual(1, 1)
- def test_something_else(self):
- self.assertEqual(2, 2)
- ##用法-测试
- suite = unittest.TestSuite()
- suite.addTest(ParametrizedTestCase.parametrize(TestOne, param=42))
- suite.addTest(ParametrizedTestCase.parametrize(TestOne, param=13))
- unittest.TextTestRunner(verbosity=2).run(suite)
- #结果
- test_something (__main__.TestOne) ... param = 42
- ok
- test_something_else (__main__.TestOne) ... ok
- test_something (__main__.TestOne) ... param = 13
- ok
- test_something_else (__main__.TestOne) ... ok
- ----------------------------------------------------------------------
- Ran 4 tests in 0.000s
- OK
或者可以使用meta类来 解决这个问题
- import unittest
- l = [["foo", "a", "a",], ["bar", "a", "a"], ["lee", "b", "b"]]
- class TestSequenceMeta(type):
- def __new__(mcs, name, bases, dict):
- def gen_test(a, b):
- def test(self):
- self.assertEqual(a, b)
- return test
- for tname, a, b in l:
- test_name = "test_%s" % tname
- dict[test_name] = gen_test(a,b)
- return type.__new__(mcs, name, bases, dict)
- class TestSequence(unittest.TestCase):
- __metaclass__ = TestSequenceMeta
- if __name__ == '__main__':
- unittest.main()
转载自:http://blog.csdn.net/hqzxsc2006/article/details/50125735