- 2 months ago 11
Python Question

Should I unittest private/protected method

This is actually language agnostic. But I'll give you context in python.

I have this parent class

class Mammal(object):
def __init__(self):
""" do some work """

def eat(self, food):
"""Eat the food"""
way_to_eat = self._eating_method()

def _eating_method(self):
"""Template method"""

def _consume(self, food):
"""Template method"""

is the only public method whereas
are actually protected methods which will be implemented by child classes.

What will you test when you have written only the

Obviously all 4 methods.

Now let's introduce a child

class Tiger(Mammal):
def _eating_method(self):
"""Template method"""

def _consume(self, food):
"""Template method"""

Look at this class. It has only 2 protected methods.

Should I test all 4 methods of
(including 2 inherited) or just test the changes introduced (only overrided 2 methods)?

What is the ideal case?


From a theoretical point of view, you only need to test public methods of your instantiable classes (in standard OOP languages). There is no point in testing the internal behaviour because all you want is "which output for that input" (for a particular method, or for the entire class). You should try to respect it as much as you can because it forces you to ask some questions about the encapsulation of your class and the provided interface which may be decisive for your architecture.

From a pragmatic point of view, you can sometimes have some abstract helper classes with no implemented concrete subclass or an abstract class factoring 90+% of its child classes and where it would be too hard to test the output without plugging into a protected method. In those kinds of cases, you can mock a subclass.

In your straightforward example, I would suggest you to only test the class Tiger (and only the public method eat).

Just a note for people thinking to TDD. In TDD, you shouldn't have started to code the class Mammal before the class Tiger because Mammal should be the result of a refactoring phase. So, you certainly woudn't have any specific test for Mammal.