单元测试断言失败时运行代码 [英] run code when unit test assert fails

查看:139
本文介绍了单元测试断言失败时运行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用unittest.TestCase中的assertEquals().我现在想做的是调用一个函数,并在断言失败时在其中执行某项操作,我想知道是否有一种方法可以做到这一点?

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?

推荐答案

通常,您不应该这样做,但是,如果您确实愿意,这里有一个简单的示例:

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)

另一种更通用的可能性是编写自己的runTest方法(如文档),它将使用try/except块包装所有测试.如果您确实需要这样做,则更建议这样做,因为这可以使您的测试代码保持整洁.

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.

这篇关于单元测试断言失败时运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆