Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Testing abstract class with concrete implementation details

I have a class containing a mixture of @abstractmethods and normal implementation methods, and I’m wondering how I should go about testing the normal implementations.

Quick Example: I’d like to test the zoo_str method, even though it depends on the abstract description method. If I have 100 animals, it seems like overkill to write a test in the Lion class, the Antelope class, the Hippo class, etc. What’s the best way to do this — my intuition says I should try to mock description, but I can’t instatntiate the class and this falls apart if the abstract method is private (_description).

class Animal:
    @abstractmethod
    def description(self) -> str:
        pass

    def zoo_str(self) -> str:
         return self.description() + "Get more info at zoo.com!"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just create a subclass.

class TestAnimal(Animal):
    def description(self):
        return "foo"


assert TestAnimal().zoo_str() == "fooGet more info at zoo.com!"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading