【问题标题】:run code when unit test assert fails [closed]当单元测试断言失败时运行代码[关闭]
【发布时间】:2014-06-24 22:35:12
【问题描述】:

我正在使用来自unittest.TestCaseassertEquals()。我现在想做的是在断言失败时调用一个函数并在那里做一些事情,不知道有没有办法做到这一点?

【问题讨论】:

    标签: python unit-testing assert testcase


    【解决方案1】:

    一般来说你不应该这样做,但如果你真的想这样做,这里有一个简单的例子:

    import unittest
    
    def testFailed():
        print("test failed")
    
    class T(unittest.TestCase):
        def test_x(self):
            try:
                self.assertTrue(False)
            except AssertionError:
                testFailed()
                raise
    
    if __name__ == "__main__":
        suite = unittest.defaultTestLoader.loadTestsFromTestCase(T)
        unittest.TextTestRunner().run(suite)
    

    另一种更通用的可能性是编写自己的runTest 方法(如the documentation 中所述),它将用try/except 块包装所有测试。如果您确实需要这样做,则更推荐这样做,因为它会使您的测试代码保持干净。

    【讨论】:

      【解决方案2】:

      抓住它:

      try:
          # something
      except AssertionError:
          # do something
      

      【讨论】:

      • 我只想在断言失败时执行代码。我认为finally下的代码在这两种情况下都会执行?
      • 是的,正确。所以只需使用 try except 和 under except 在调用所需函数后引发异常
      猜你喜欢
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多