run code when unit test assert fails [closed]

不打扰是莪最后的温柔 提交于 2019-12-03 17:24:03

In general you shouldn't do it, but if you really want to, here is a simple example:

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)

Another, more generic possibility is to write your own runTest method (as mentioned in the documentation) which will wrap all tests with try/except block. This would be even more recommended if you really need to do it, as it will keep your test code clean.

Catch it:

try:
    # something
except AssertionError:
    # do something
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!