Python unittest Setup and Teardown: Complete Guide to setUp, tearDown, setUpClass, and tearDownClass

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 NameTypeTimingMain Usage
setUpInstance MethodImmediately before each test methodInitializing variables, clearing lists
tearDownInstance MethodImmediately after each test methodDeleting temporary data, resetting state
setUpClassClass MethodOnce at the start of the test classDatabase connection, loading heavy resources
tearDownClassClass MethodOnce at the end of the test classDisconnecting 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

  1. setUpClass is executed only once at the very beginning.
  2. Then, the test methods (test_feature_a, test_feature_b) are executed. Notice that setUp runs before and tearDown runs after each test method every time.
  3. After all tests are finished, tearDownClass is 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 @classmethod and 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.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次