Search code examples
pythonunit-testingasserttestcase

run code when unit test assert fails


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?


Solution

  • 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.