I have a class like the following:
class Positive(object):
def __init__(self, item):
self._validate_item(item)
self.item = item
def _validate_item(self, item):
if item <= 0:
raise ValueError("item should be positive.")
I’d like to write a unit test for _validate_item(), like the following:
class PositiveTests(unittest.TestCase):
def test_validate_item_error(self):
self.assertRaises(
ValueError,
Positive._validate_item,
0
)
Unfortunately, this won’t work because the unit test only passes 0 to the method, instead of a class instance (for the self parameter) and the 0. Is there any solution to this other than having to test this validation method indirectly via the __init__() of the class?
If you’re not using self in the method’s body, it’s a hint that it might not need to be a class member. You can either move the _validate_item function into module scope:
Or if it really has to stay in the class, the mark the method static:
Your test should then work as written.