python unittest单元测试框架中,如何对一个testcase参数化,具体如何实 ...
发布网友
发布时间:2022-05-06 12:54
我来回答
共2个回答
热心网友
时间:2022-04-18 07:23
#首先pyunit不像junit一样支持参数化测试。。。不过不是不能实现,只是pyunit的作者想让#这个东西变得尽量简单。所以不去实现。当然这个pyhon语言足够动态,你可以自己去实现
#外部输入参数测试。
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
当然最好的方法就是用别人写的东西。。。
https://github.com/taykey/nose-ittr
这个拿去,不谢
热心网友
时间:2022-04-18 08:41
__init 。这个题我是想测试一下的