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
TestConstructionI will be happy for example if there is a way to set TestConstruction to be executed before the other tests.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With