【问题标题】:In Python unittest, how can I call a function after all tests in a TestCase have been executed?在 Python unittest 中,如何在执行了 TestCase 中的所有测试后调用函数?
【发布时间】:2019-01-25 04:00:18
【问题描述】:

我在 Python 中运行一些单元测试,并希望在所有测试用例都运行后调用一个函数。

class MyTestCase(TestCase):
    def setUp(self):
        self.credentials = credentials

    def tearDown(self):
        print("finished running " + self._testMethodName)

    def tearDownModule(self):
        print("finished running all tests")

    def test_1(self):
        #do something

    def test_2(self):
        #do something else

setUp 和 tearDown 在每个单独的测试之前和之后运行。然而,我想在所有测试完成运行后调用一个函数(在本例中为 test_1 和 test_2)。

从文档看来,tearDownModule() 函数应该这样做,但似乎没有调用它。

【问题讨论】:

  • 你的意思是def teardown_class??

标签: python python-unittest


【解决方案1】:

tearDownModule 用于模块范围,而不是作为方法。相反,你可能想要tearDownClass:

class MyTestCase(TestCase):

    @classmethod
    def tearDownClass(cls):
        ...

【讨论】:

  • 我真的试过了,但忘了装饰器!谢谢。
  • 我可以将'self'传递给这个函数吗?基本上我需要访问一个我在每次拆解调用中更新的变量。
  • 不,你不应该。最好避免测试单元之间的任何可变状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多