Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to create an instance of class to be tested with unittest?

Say I have:

class Calculator():
    def divide (self, divident, divisor):
        return divident/divisor`

And I want to test its divide method using Python 3.4 unittest module.

Does my code have to have instantiation of class to be able to test it? Ie, is the setUp method needed in the following test class:

class TestCalculator(unittest.TestCase):
    def setUp(self):
        self.calc = src.calculator.Calculator()
    def test_divide_by_zero(self):
        self.assertRaises(ZeroDivisionError, self.calc(0, 1))
like image 727
julka Avatar asked Mar 16 '23 22:03

julka


2 Answers

As it has a self parameter it is an instance method, so you need an instance.

If it didn't have self you could make it a @classmethod or a @staticmethod, see what's the difference.

As you don't use the self parameter it should probably not be an instance method. But you could just have a function instead and no class at all:

# calculator.py

def divide(dividend, divisor):
    return dividend / divisor
like image 73
Peter Wood Avatar answered Mar 29 '23 22:03

Peter Wood


Yes, you do. Whether you re-instantiate the class for each test case, or only once in setUp, depends on whether you need a fresh instance of the class for each test (for example, because your class carries a lot of internal state).

like image 32
michel-slm Avatar answered Mar 30 '23 00:03

michel-slm