run code when unit test assert fails [closed]

99封情书 提交于 2019-12-09 13:33:08

问题


I'm using assertEquals() from unittest.TestCase. What I want to do now is to call a function and do something there when the assertion fails, I wonder if there's a way of doing this?


回答1:


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.




回答2:


Catch it:

try:
    # something
except AssertionError:
    # do something


来源:https://stackoverflow.com/questions/24397456/run-code-when-unit-test-assert-fails

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