Python - Testing an abstract base class

前端 未结 6 1337
醉话见心
醉话见心 2020-12-04 16:27

I am looking for ways / best practices on testing methods defined in an abstract base class. One thing I can think of directly is performing the test on all concrete subclas

6条回答
  •  情歌与酒
    2020-12-04 17:06

    You can use multiple inheritance practice to have access to the implemented methods of the abstract class. Obviously following such design decision depends on the structure of the abstract class since you need to implement abstract methods (at least bring the signature) in your test case.

    Here is the example for your case:

    class Abstract(object):
    
        __metaclass__ = abc.ABCMeta
    
        @abc.abstractproperty
        def id(self):
            return
    
        @abc.abstractmethod
        def foo(self):
            print("foo")
    
        def bar(self):
            print("bar")
    
    class AbstractTest(unittest.TestCase, Abstract):
    
        def foo(self):
            pass
        def test_bar(self):
            self.bar()
            self.assertTrue(1==1)
    

提交回复
热议问题