Check object initialization and use it

I have a class and I want to test it with the built-in unittest module. Specifically, I want to test if I can create intuitions without throwing errors, and if I can use them.

The problem is that creating these objects is quite slow, so I can create an object in a method setUpClass

and reuse it.

@classmethod
def setUpClass(cls):
    cls.obj = MyClass(argument)

def TestConstruction(self):
    obj = MyClass(argument)

def Test1(self):
    self.assertEqual(self.obj.metohd1(), 1)

      

point

  • I create 2x expensive object
  • setUp are calls before TestConstruction, so I cannot test for failure inside TestConstruction

I'll be happy, for example, if there is a way to set it TestConstruction

to run before other tests.

+3


source to share


1 answer


Why not test both initialization and functionality in the same test?

class MyTestCase(TestCase):
    def test_complicated_object(self):
        obj = MyClass(argument)
        self.assertEqual(obj.method(), 1)

      

Alternatively, you can do one test for initializing the case object and one test case for other tests. This means that you need to create the object twice, but this might be an acceptable tradeoff:

class CreationTestCase(TestCase):
    def test_complicated_object(self):
        obj = MyClass(argument)

class UsageTestCase(TestCase):
    @classmethod
    def setupClass(cls):
        cls.obj = MyClass(argument)

    def test_complicated_object(self):
        self.assertEqual(obj.method(), 1)

      



Please note that if you are trying to modify an object you will run into a problem.

Alternatively you can do this, but again, I would not recommend it

class MyTestCase(TestCase):
    _test_object = None

    @classmethod
    def _create_test_object(cls):
        if cls._test_object is None:
            cls._test_object = MyClass(argument)
        return cls._test_object

    def test_complicated_object(self):
        obj = self._create_test_object()
        self.assertEqual(obj.method(), 1)

    def more_test(self):
        obj = self._create_test_object()
        # obj will be cached, unless creation failed

      

+2


source







All Articles