Instantiate Python unittest.TestCase with arguments

…衆ロ難τιáo~ 提交于 2019-12-04 23:59:11

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.

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()

According to "Python unit testing: parametrized test cases", published in Eli Bendersky's blog:

Python’s standard unittest library is great and I use it all the time. One thing missing from it, however, is a simple way of running parametrized test cases. In other words, you can’t easily pass arguments into a unittest.TestCase from outside.

Eli's solution is inheriting unittest.TestCase into ParametrizedTestCase. I'm not sure about copyright issues, so I won't copy-paste the code here.

If there is any better solution, I will be happy to accept it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!