Skip to content

Class-level Setup - setUpClass() and tearDownClass()

Why class-level setup?

Sometimes setup is expensive:

  • loading a large fixture file
  • initializing test data

Use setUpClasssetUpClass to run once per class.

Example

setupclass_teardownclass.py
import unittest
 
 
class TestExpensiveSetup(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.data = list(range(1000))
 
    @classmethod
    def tearDownClass(cls):
        cls.data = []
 
    def test_sum(self):
        self.assertEqual(sum(self.data), sum(range(1000)))
 
    def test_len(self):
        self.assertEqual(len(self.data), 1000)
setupclass_teardownclass.py
import unittest
 
 
class TestExpensiveSetup(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.data = list(range(1000))
 
    @classmethod
    def tearDownClass(cls):
        cls.data = []
 
    def test_sum(self):
        self.assertEqual(sum(self.data), sum(range(1000)))
 
    def test_len(self):
        self.assertEqual(len(self.data), 1000)

Caution

  • Don’t share mutable state between tests unless read-only.
  • Tests should not depend on run order.

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did