Is there a difference between using tearDown and setUp versus __init__
and __del__
when using the pyUnit testing framework? If so, what is it exactly and what is the preferred method of use?
The setUp method is run prior to each test in the class. tearDown is run at the end of every test. These methods are optional.
The setUp() runs before every test method in the test class. The tearDown() runs after every test method in the test class.
For that it has two important methods, setUp() and tearDown() . setUp() — This method is called before the invocation of each test method in the given class. tearDown() — This method is called after the invocation of each test method in given class.
Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.
setUp
is called before every test, and tearDown
is called after every test. __init__
is called once when the class is instantiated -- but since a new TestCase
instance is created for each individual test method, __init__
is also called once per test.
You generally do not need to define __init__
or __del__
when writing unit tests, though you could use __init__
to define a constant used by many tests.
This code shows the order in which the methods are called:
import unittest import sys class TestTest(unittest.TestCase): def __init__(self, methodName='runTest'): # A new TestTest instance is created for each test method # Thus, __init__ is called once for each test method super(TestTest, self).__init__(methodName) print('__init__') def setUp(self): # # setUp is called once before each test # print('setUp') def tearDown(self): # # tearDown is called once after each test # print('tearDown') def test_A(self): print('test_A') def test_B(self): print('test_B') def test_C(self): print('test_C') if __name__ == '__main__': sys.argv.insert(1, '--verbose') unittest.main(argv=sys.argv)
prints
__init__ __init__ __init__ test_A (__main__.TestTest) ... setUp test_A tearDown ok test_B (__main__.TestTest) ... setUp test_B tearDown ok test_C (__main__.TestTest) ... setUp test_C tearDown ok ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With