4

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))
julka
  • 1,172
  • 2
  • 13
  • 29

2 Answers2

4

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
Community
  • 1
  • 1
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
  • Perhaps my example was oversimplified, but your `As it has a self parameter it is an instance method, so you need an instance.` answers the question. – julka Feb 26 '15 at 17:58
3

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).

michel-slm
  • 9,438
  • 3
  • 32
  • 31
  • However, this method doesn't use any internal state, and the class doesn't carry any. – Peter Wood Feb 26 '15 at 10:44
  • @PeterWood indeed. Just thought I'd mention that in case a further refinement introduces, say, memory variables to this calculator – michel-slm Feb 26 '15 at 11:31