使用参数实例化 Python unittest.TestCase [英] Instantiate Python unittest.TestCase with arguments
问题描述
我想遍历一个项目列表,并对每个项目运行一个断言.一个例子可能是检查列表中的每个数字是否都是奇数.
I would like to iterate over a list of items, and run an assertion on each of them. One example might be checking whether each number in a list is odd.
TestCase
:
class TestOdd(unittest.TestCase):
def runTest(self):
"""Assert that the item is odd"""
self.assertTrue( NUMBER %2==1, "Number should be odd")
测试套件
:
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestOdd())
# I would like to have:
# suite.addTest(TestOdd(1))
# suite.addTest(TestOdd(2))
# suite.addTest(TestOdd(3))
# ...
unittest.main()
如何使用参数实例化 TestOdd
对象 - 例如,要测试的数字?
How can I instantiate a TestOdd
object with an argument - for example, the number to be tested?
更新:根据 2011 年的一篇博客文章(作为答案发布),没有用于参数化测试的内置机制.我很乐意接受任何更简洁的解决方案.
推荐答案
同样可以使用类属性来实现.
Same can be achieved using class attributes.
class TestOdd1(unittest.TestCase):
NUMBER=1
def runTest(self):
"""Assert that the item is odd"""
self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")
class TestOdd2(TestOdd1):
NUMBER=2
if __name__ == '__main__':
unittest.main()
单元测试会自动发现它们,因此无需创建套件.
The unittesting will discover them automatically, so no need to create a suite.
如果你想避免使用TestCase作为基类,你可以使用多重继承:
If you want to avoid using a TestCase for base class, you can use multiple inheritance:
from unittest import TestCase, main
class TestOdd:
def runTest(self):
"""Assert that the item is odd"""
self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")
class TestOdd1(TestOdd, TestCase):
NUMBER=1
class TestOdd2(TestOdd, TestCase):
NUMBER=2
if __name__ == '__main__':
main()
这篇关于使用参数实例化 Python unittest.TestCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!