unittest.TestCase Lifecycle
Sometimes, when doing tests, we might need to do something:
- before/after all tests or
- before/after each test
This concept is almost universal and it is implemented similarly in certain test frameworks such as JUnit (in Java) or unittest (in Python) - this later, the one we want to explore.
In our example we will build a base test class - called SampleTestCase
- that will implement the main life-cycle methods of a TestCase
.
class SampleTestCase(TestCase):
@classmethod
def setUpClass(cls) -> None:
print("setUpClass")
def setUp(self) -> None:
print("setUp")
def tearDown(self) -> None:
print("tearDown")
@classmethod
def tearDownClass(cls) -> None:
print("tearDownClass")
Looking to SampleTestCase
code, we see four methods:
setUpClass
andtearDownClass
will run before and after all the test cases are run (respectively)setup
andtearDown
will run before and after each test case is run (respectively)
If we had a test case like this:
class ConcreteImplementationOfTestCase(SampleTestCase):
def test_do_return_equal_when_true_equals_1(self):
self.assertEqual(True, 1)
def test_do_return_equal_when_true_equals_0(self):
self.assertEqual(False, 0)
The output would be the following
$ python -m unittest test_unnittest_lifecycle_methods.py
setUpClass
setUp
tearDown
.setUp
tearDown
.tearDownClass
Simple, and very powerful!