5
如何在Python2.7中的unittest中显示由assertRaises()捕获的错误消息?
为了确保来自我的模块的错误消息是有用的,我想查看assertRaises()捕获的所有错误消息。今天,我对每个assertRaises()都这样做,但是由于测试代码中有很多代码,因此变得非常乏味。 如何打印所有assertRaises()的错误消息?我研究了http://docs.python.org/library/unittest.html上的文档,但没有弄清楚如何解决它。我可以以某种方式猴子断言assertRaises()方法吗?我宁愿不更改测试代码中的所有assertRaises()行,因为我最经常以标准方式使用测试代码。 我猜这个问题与Python unittest有关:如何在Exceptions中测试参数? 我今天就是这样做的。例如: #!/usr/bin/env python def fail(): raise ValueError('Misspellled errrorr messageee') 和测试代码: #!/usr/bin/env python import unittest import failure class TestFailureModule(unittest.TestCase): def testFail(self): self.assertRaises(ValueError, failure.fail) if __name__ == '__main__': unittest.main() 要检查错误消息,我只需将assertRaises()中的错误类型更改为例如IOError。然后我可以看到错误消息: E ====================================================================== ERROR: testFail (__main__.TestFailureModule) ---------------------------------------------------------------------- Traceback (most recent call last): File "test_failure.py", line 8, in testFail self.assertRaises(IOError, …