Python unit test with base and sub class

前端 未结 15 2282
独厮守ぢ
独厮守ぢ 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:13

    What are you trying to achieve? If you have common test code (assertions, template tests, etc), then place them in methods which aren't prefixed with test so unittest won't load them.

    import unittest
    
    class CommonTests(unittest.TestCase):
          def common_assertion(self, foo, bar, baz):
              # whatever common code
              self.assertEqual(foo(bar), baz)
    
    class BaseTest(CommonTests):
    
        def testCommon(self):
            print 'Calling BaseTest:testCommon'
            value = 5
            self.assertEquals(value, 5)
    
    class SubTest1(CommonTests):
    
        def testSub1(self):
            print 'Calling SubTest1:testSub1'
            sub = 3
            self.assertEquals(sub, 3)
    
    class SubTest2(CommonTests):
    
        def testSub2(self):
            print 'Calling SubTest2:testSub2'
            sub = 4
            self.assertEquals(sub, 4)
    
    if __name__ == '__main__':
        unittest.main()
    

提交回复
热议问题