How to unittest unittest TestCases

点点圈 提交于 2019-12-10 21:17:22

问题


I have a unittest.TestCase child, which defines several domain specific assert Checks. I would like to run some unittests to unittest this functionality to control that everything work on future updates.

class MyBaseTestCase(unittest.TestCase):
    def setUp(self):
        ...
    def tearDown(self):
        ...
    def run(self, result):
        ...
    def assertSpec(self, condition, message):
        ...

I want to instantiate MyBaseTestCase in other unit test, like this:

class TestBase(unittest.TestCase):
    def test_assertSpec(self):
        self.testclass = MyBaseTestCase()
        self.assertRaises(AssertionError, self.testclass.assertSpec, False)

I'm encountering multiple different errors, when doing this, so my question is what is a common practice for unittesting custom unittest functions?

In case it helps:

$ jython
>>> import sys
>>> sys.version
'2.5.2 (Release_2_5_2:7206, Mar 2 2011, 23:12:06) \n[Java HotSpot(TM) Server VM (Sun Microsystems Inc.)]'

回答1:


Not sure if there's anything Jython specific that would break this, but I would do something like this:

import StringIO
import unittest


# The TestCase subclass to test    
class MyBaseTestCase(unittest.TestCase):
    def assertSpec(self, thing):
        assert thing == 123


# The testcase for MyBaseTestCase
class TestMyTest(unittest.TestCase):
    def test_assetSpec(self):
        """Ensure assertSpec works
        """

        class _TestSpec(MyBaseTestCase):
            def test_failure_case(self):
                 self.assertSpec(121)
            def test_success_case(self):
                 self.assertSpec(123)

        # Load tests from _TestSpec
        loader = unittest.TestLoader()
        suite = loader.loadTestsFromTestCase(_TestSpec)

        # Create runner, and run _TestSpec
        io = StringIO.StringIO()
        runner = unittest.TextTestRunner(stream = io)
        results = runner.run(suite)

        # Should be one failed test, and one passed test
        self.assertEquals(results.testsRun, 2)
        self.assertEquals(len(results.failures), 1)

if __name__ == "__main__":
    unittest.main()


来源:https://stackoverflow.com/questions/8308435/how-to-unittest-unittest-testcases

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