PyUnit tearDown and setUp vs __init__ and __del__
Is there a difference between using tearDown and setUp versus __init__
and __del__
when using the pyUn开发者_StackOverflow中文版it testing framework? If so, what is it exactly and what is the preferred method of use?
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
精彩评论