问题
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