在我的项目中,我有一个 TestCase 的子类(称之为 BaseTest),它会做一些准备然后重置测试环境,以及大量实际的测试用例子类(大约 80 个),每个子类都有自己独特的设置方法。
我希望每个单独的测试用例子类在它们的 setUp 方法结束时调用一个特定的 Hook 。我想在不更改其中每一种方法的情况下执行此操作。
基本上,情况看起来大致像这个示例文件:
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
的结果在每次打印“prepping a”或“prepping b”后打印“in post setup hook”,但不修改 TestFeatureA 或测试功能 B.这能做到吗?
请注意,我使用的是 python 3.6。我认为这不会在 python 2.x 中运行。
最佳答案
您可以覆盖 run
BaseTest(TestCase)
方法调用post_setup_hook
after the setUp
.
只需将 run
方法复制粘贴到 BaseTest
中,并在 setUp
运行后添加 post_setup_hook
调用。
关于python - 如何让每个TestCase在setUp后都调用一个hook?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43674038/