Python unit test with base and sub class

前端 未结 15 2317
独厮守ぢ
独厮守ぢ 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 18:53

    Change the BaseTest method name to setUp:

    class BaseTest(unittest.TestCase):
        def setUp(self):
            print 'Calling BaseTest:testCommon'
            value = 5
            self.assertEquals(value, 5)
    
    
    class SubTest1(BaseTest):
        def testSub1(self):
            print 'Calling SubTest1:testSub1'
            sub = 3
            self.assertEquals(sub, 3)
    
    
    class SubTest2(BaseTest):
        def testSub2(self):
            print 'Calling SubTest2:testSub2'
            sub = 4
            self.assertEquals(sub, 4)
    

    Output:

    Ran 2 tests in 0.000s

    Calling BaseTest:testCommon Calling
    SubTest1:testSub1 Calling
    BaseTest:testCommon Calling
    SubTest2:testSub2

    From the documentation:

    TestCase.setUp()
    Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.

提交回复
热议问题