When performing unit tests, you often need “pre-processing” such as connecting to a database or preparing initial data before running tests. You also need “post-processing” to delete temporary files or close connections after tests finish.
Python’s unittest framework provides four special methods to automatically execute these processes.
This article explains the role, execution timing, and implementation of each method.
List of 4 Setup and Teardown Methods
The setup and teardown methods available in unittest are classified by their execution timing (per method or per class).
| Method Name | Type | Timing | Main Usage |
setUp | Instance Method | Immediately before each test method | Initializing variables, clearing lists |
tearDown | Instance Method | Immediately after each test method | Deleting temporary data, resetting state |
setUpClass | Class Method | Once at the start of the test class | Database connection, loading heavy resources |
tearDownClass | Class Method | Once at the end of the test class | Disconnecting database, releasing resources |
Verifying the Execution Order
Let’s run some code to see the order in which these methods are called.
Note that setUpClass and tearDownClass require the @classmethod decorator.
import unittest
class TestLifecycleSample(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("\n=== setUpClass: Global initialization (Runs once at start) ===")
@classmethod
def tearDownClass(cls):
print("=== tearDownClass: Global cleanup (Runs once at end) ===")
def setUp(self):
print(" -> setUp: Preparation for test method")
def tearDown(self):
print(" <- tearDown: Cleanup for test method")
def test_feature_a(self):
print(" [Test A] Running...")
def test_feature_b(self):
print(" [Test B] Running...")
if __name__ == "__main__":
unittest.main()
Execution Result:
=== setUpClass: Global initialization (Runs once at start) ===
-> setUp: Preparation for test method
[Test A] Running...
<- tearDown: Cleanup for test method
-> setUp: Preparation for test method
[Test B] Running...
<- tearDown: Cleanup for test method
=== tearDownClass: Global cleanup (Runs once at end) ===
Key Behavior Points
setUpClassis executed only once at the very beginning.- Then, the test methods (
test_feature_a,test_feature_b) are executed. Notice thatsetUpruns before andtearDownruns after each test method every time. - After all tests are finished,
tearDownClassis executed only once at the very end.
Practical Usage Strategy
When to use setUp / tearDown
Use these when you want to return to a “clean slate” state every time so that test methods do not affect each other.
- Emptying test lists or dictionaries.
- Creating a new instance for each test.
When to use setUpClass / tearDownClass
Use these when the process is heavy and running it every time would make the tests take too long.
- Establishing a connection to a database.
- Launching a web browser (e.g., using Selenium).
- Loading large configuration files.
Summary
setUp/tearDown: Executed every time for each test method. Important for maintaining test independence.setUpClass/tearDownClass: Executed only once for the entire class. Requires@classmethodand is used for sharing heavy initialization processes.
By using these appropriately, you can write test code that is both reliable and efficient in terms of execution speed.
