在我的项目中,我有一个TestCase的子类(称为BaseTest),它可以做一些准备工作,然后重置测试环境,还有许多实际的测试用例子类(约80个),每个子类都有自己独特的setUp方法。
我希望每个单独的测试用例子类在其setUp方法的末尾调用一个特定的钩子。我想这样做而不更改这些方法的每一种。
基本上,情况大致类似于以下示例文件:
import unittest
class BaseTest(unittest.TestCase):
def setUp(self):
super().setUp()
print('prepping env')
def tearDown(self):
super().tearDown()
print('resetting env')
def post_setup_hook(self):
print('in post_setup_hook')
class TestFeatureA(BaseTest):
def setUp(self):
super().setUp()
print('prepping a')
def tearDown(self):
super().tearDown()
def test_0(self):
print('testing a0')
def test_1(self):
print('testing a1')
class TestFeatureB(BaseTest):
def setUp(self):
super().setUp()
print('prepping b')
def tearDown(self):
super().tearDown()
def test_0(self):
print('testing b0')
def test_1(self):
print('testing b1')
if __name__ == '__main__':
unittest.main()
我希望运行
python -m unittest example
的结果在每次打印“准备a”或“准备b”之后打印“在安装后挂钩”,但不修改TestFeatureA或TestFeatureB。能做到吗?请注意,我正在使用python 3.6。我认为这不会在python 2.x中运行。
最佳答案
您可以覆盖run
的BaseTest(TestCase)
方法来调用post_setup_hook
after the setUp
。
只需将run
方法复制粘贴到BaseTest
中,并在post_setup_hook
运行后添加setUp
调用。