Python unit test with base and sub class

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

    Here is a solution that uses only documented unittest features an that avoids having a "skip" status in your test results:

    class BaseTest(unittest.TestCase):
    
        def __init__(self, methodName='runTest'):
            if self.__class__ is BaseTest:
                # don't run these tests in the abstract base implementation
                methodName = 'runNoTestsInBaseClass'
            super().__init__(methodName)
    
        def runNoTestsInBaseClass(self):
            pass
    
        def testCommon(self):
            # everything else as in the original question
    
    

    How it works: per the unittest.TestCase documentation, "Each instance of TestCase will run a single base method: the method named methodName." The default "runTests" runs all the test* methods on the class—that's how TestCase instances normally work. But when running in the abstract base class itself, you can simply override that behavior with a method that does nothing.

    A side effect is your test count will increase by one: the runNoTestsInBaseClass "test" gets counted as a successful test when it's run on BaseClass.

    (This also works in Python 2.7, if you're still on that. Just change super() to super(BaseTest, self).)

提交回复
热议问题