Python unit test with base and sub class

前端 未结 15 2286
独厮守ぢ
独厮守ぢ 2020-11-28 18:44

I currently have a few unit tests which share a common set of tests. Here\'s an example:

import unittest

class BaseTest(unittest.TestCase):

    def testCo         


        
15条回答
  •  执笔经年
    2020-11-28 19:03

    Do not use multiple inheritance, it will bite you later.

    Instead you can just move your base class into the separate module or wrap it with the blank class:

    class BaseTestCases:
    
        class BaseTest(unittest.TestCase):
    
            def testCommon(self):
                print('Calling BaseTest:testCommon')
                value = 5
                self.assertEqual(value, 5)
    
    
    class SubTest1(BaseTestCases.BaseTest):
    
        def testSub1(self):
            print('Calling SubTest1:testSub1')
            sub = 3
            self.assertEqual(sub, 3)
    
    
    class SubTest2(BaseTestCases.BaseTest):
    
        def testSub2(self):
            print('Calling SubTest2:testSub2')
            sub = 4
            self.assertEqual(sub, 4)
    
    if __name__ == '__main__':
        unittest.main()
    

    The output:

    Calling BaseTest:testCommon
    .Calling SubTest1:testSub1
    .Calling BaseTest:testCommon
    .Calling SubTest2:testSub2
    .
    ----------------------------------------------------------------------
    Ran 4 tests in 0.001s
    
    OK
    

提交回复
热议问题