What is the difference between setUp() and setUpClass() in Python unittest?

etja picture etja · May 15, 2014 · Viewed 37.1k times · Source

What is the difference between setUp() and setUpClass() in the Python unittest framework? Why would setup be handled in one method over the other?

I want to understand what part of setup is done in the setUp() and setUpClass() functions, as well as with tearDown() and tearDownClass().

Answer

Benjamin Hodgson picture Benjamin Hodgson · May 15, 2014

The difference manifests itself when you have more than one test method in your class. setUpClass and tearDownClass are run once for the whole class; setUp and tearDown are run before and after each test method.

For example:

class Example(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("setUpClass")

    def setUp(self):
        print("setUp")

    def test1(self):
        print("test1")

    def test2(self):
        print("test2")

    def tearDown(self):
        print("tearDown")

    @classmethod
    def tearDownClass(cls):
        print("tearDownClass")

When you run this test, it prints:

setUpClass
setUp
test1
tearDown
.setUp
test2
tearDown
.tearDownClass

(The dots (.) are unittest's default output when a test passes.) Observe that setUp and tearDown appear before and after test1 and test2, whereas setUpClass and tearDownClass appear only once, at the beginning and end of the whole test case.