Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test initialization of object and use it [closed]

I have an class and I want to test it with the built in unittest module. In particular I want to test if I can create intances without throwing errors and if I can use them.

The problem is that the creation of this objects is quite slow, so I can create the object in the setUpClass method and reuse them.

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

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

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

the point is

  1. I am creating 2 times the expensive object
  2. setUp is calles before TestConstruction, so I cannot check the failure inside TestConstruction

I will be happy for example if there is a way to set TestConstruction to be executed before the other tests.

like image 415
Ruggero Turra Avatar asked Jan 01 '26 06:01

Ruggero Turra


1 Answers

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 have one test for the case object initialization, and one test case for the other tests. This does mean you have to create the object twice, but it 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)

Do note that if you methods mutate the object, you're going to get into trouble.

Alternatively, you can do this, but again, I wouldn't 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
like image 164
Thomas Orozco Avatar answered Jan 06 '26 02:01

Thomas Orozco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!