在使用 pyUnit 测试框架时,使用 tearDown 和 setUp 与使用 __init__
和 __del__
有区别吗?如果是这样,它到底是什么?首选的使用方法是什么?
最佳答案
setUp
在每次测试前调用,tearDown
在每次测试后调用。
__init__
在类被实例化时被调用一次——但是因为 a new
TestCase
instance is created for each individual test method , __init__
是
每次测试也调用一次。
写unit时一般不需要定义__init__
或__del__
测试,尽管您可以使用 __init__
来定义许多测试使用的常量。
此代码显示调用方法的顺序:
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)
打印
__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
关于python - PyUnit 拆解和设置与 __init__ 和 __del__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2344772/