开发者

Unit testing: Does it make sense to test parent object methods?

开发者 https://www.devze.com 2023-02-27 07:36 出处:网络
Let\'s say I am using a framework that has a class called Animal. class Animal(object): def speak(self):

Let's say I am using a framework that has a class called Animal.

class Animal(object):
    def speak(self):
        logging.info(self.sound)

I have to subclass this object in order to use it and it might look something like this:

class Dog(Animal):
    def __init__(self):
        self.sound = 'Woof Woof'

The way I see it I could do two things. The first is something like like this:

dog = Dog()
assert dog.sound == 'Woof Woof'

The second option is to mock out logging.info and check if it was called. I have mixed feelings about both of them.

The first one feels like I am just testing my configuration and the second one feels like I am not actually testing the object I want.

I am using this simple example because maybe then people that don't use Django could give me some pointers. The real problem I am having involves Django generic views.

开发者_运维百科

For example I can have this template view:

class HomeView(TemplateView):
    template_name = 'home.html'

Do I just test if template_name has the correct value or do I use the test client to do a higher level test to test the complete view?


No, make sure the parent object is tested properly (with mocking if necessary) and test the sub-objects methods separately. This fits with the encapsulation concept (making matters local).

If you don't, a large project with many classes will drain all your coding resources for no added value.


In your simple example I would probably test the parent method. But in your Django case that would mean testing Django. And that's not your job! ;-) For me that's one of the big problems of unit testing: Don't test other peoples code or 3rd part libs. Make sure that your part is correct. Might sound obvious, but is not that easy in real live - at least in my experience.


The test that you show is exactly correct - you are repeating the string literal 'Woof Woof' in your test.

You could have a similar test for Animal:

animal = Animal()
animal.sound = 'sound'
animal.speak()
# test that detects log contains 'sound'

You could also have a test that takes a list of Animals, eg [Dog, Cat, ...] and detects that an instance of each speaks its sound.

for animalClass in AnimalList:
    animal = animalClass()
    animal.speak()
    # test that detects log contains animal.sound
0

精彩评论

暂无评论...
验证码 换一张
取 消