hummelila
hummelila

Reputation: 38

Why do I receive the following AttributeError when testing a class method with unittest: 'class' object has no attribute 'testing method'?

For the sake of practicing to code, I am trying to program a very simple game. When trying to run a test on a (private) class method, I receive the following error: AttributeError: 'LivingBeing' object has no attribute '_Test_Class_Methods__lose_hp'

More elaborate:

I have a class named "LivingBeing" in the file classes.py.

class LivingBeing:

def __init__(self, name, hp=100):
    self.name = name
    self.hp = hp

def __lose_hp(self, number=20, decimal_percentage=1):
    self.hp = self.hp - (21 - number)*decimal_percentage
    return self.hp

Now I would like to test said __lose_hp method, and I tried this with the following code:

import sys, unittest
sys.path.append("/Users/angel/OneDrive/Dokumente/Studium/CL/Programmieren/git_projects/fantasticgame/")

from classes import LivingBeing

class Test_Class_Methods(unittest.TestCase):

    def setUp(self):
        self.livingbeing = LivingBeing("Life")

    def test_lose_hp(self):
        self.assertEqual(self.livingbeing.__lose_hp(20), 99, "Should be 99")

if __name__ == "__main__":
    unittest.main()

What I tried so far:

Looked like this:

class Test_Class_Methods(unittest.TestCase, LivingBeing):

    def setUp(self):
        self.livingbeing = LivingBeing("Life")

    def test_lose_hp(self):
        self.assertEqual(self.livingbeing.__lose_hp(20), 99, "Should be 99")

This being my first question, I hope it's as complete and concise as it should be, and I am thankful for any pointers to help with said error.

EDIT: I changed the method to being public instead of private, and with that change, it now works. If I happen to find a good guide on how to write tests for private methods, I might link it here for future answer-seekers.

Upvotes: 1

Views: 929

Answers (1)

staticint
staticint

Reputation: 62

I know it's a bit too late but I was facing the same AttributeError as yours. Removing double underscore from the beggining of the function I wanted to test helped me.

Upvotes: 1

Related Questions