lundi 25 mai 2015

What's the right way of unit-testing a python class?

I'm not sure what's the best way to build independent unit tests on methods of a python class. Here is a trivial example:

class MyClass(object):
  def __init__(self, data):
    self.data = data

  def myMethod(self):
    #do something
    return True

I'm building unit tests like this:

class TestMyClass(unittest.TestCase):
  def test_init(self):
    mydata = mock.Mock()
    c = MyClass(mydata)
    self.assertEqual(c.data, mydata)

  def test_myMethod(self):
    mydata = mock.Mock()
    c = MyClass(mydata)
    self.assertTrue(c.myMethod())

OK, this is very trivial... but the point is: test_myMethod() depends on __init__ because I have to instantiate the object itself: it isn't really isolated. The only way that has come to my mind to solve this issue is mocking the object itself... but how can I test a real method on a mocked object?

I know that in real world a perfect isolation could be impossible, but I'm curious to know if there are better ways.

Aucun commentaire:

Enregistrer un commentaire