python - 如何让每个TestCase在setUp后都调用一个hook?

标签 python python-3.x unit-testing testing python-unittest

在我的项目中,我有一个 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/

相关文章:

python - 如何读取本地存储中的文件(如内存中的文件)并将其附加到电子邮件中?

python - 使用 pyqtgraph 实时绘制许多子图

python - 减少 django 项目的 QuerySet 数量

python - Process.WaitforExit() 参数上的 IronPython 错误

unit-testing - 单元测试框架 - 解析实体名称时出错

Python - 连续转换日期时间对象,同时保持非日期时间对象相同

python-3.x - 重命名列正则表达式,如果不匹配则保留名称

Python 3.3 将 key 发送到 Visual Boy Advance

javascript - 使用 Sinon 在同一文件中 stub 方法

python - 如何模拟我无法访问的对象属性?