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()
.
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
respectively, whereas setUpClass
and tearDownClass
appear only once, at the beginning and end of the whole test case.
After reading both question and the accepted answer, I think some supplement can be made.
Q: Why would setup be handled in one method over the other?
A: It's because the test method may need preliminary and the preliminary varies from test method to test method.
For example, take below code from https://www.tutorialspoint.com/unittest_framework/unittest_framework_api.htm as a sample:
import unittest
class simpleTest2(unittest.TestCase):
def setUp(self):
self.a = 10
self.b = 20
name = self.shortDescription()
if name == "add":
self.a = 10
self.b = 20
print name, self.a, self.b
if name == "sub":
self.a = 50
self.b = 60
print name, self.a, self.b
def tearDown(self):
print '\nend of test',self.shortDescription()
def testadd(self):
"""add"""
result = self.a+self.b
self.assertTrue(result == 30)
def testsub(self):
"""sub"""
result = self.a-self.b
self.assertTrue(result == -10)
if __name__ == '__main__':
unittest.main()
The method testadd
and testsub
needs different input and we can set the value of the input respectively in setUp
method.