【问题标题】:assertRaises not getting matchedassertRaises 没有得到匹配
【发布时间】:2017-02-17 11:03:28
【问题描述】:

我正在学习 python 联合并想测试异常处理。为什么 assertRaises 没有被抓住而我的单元测试失败了?

def abc(xyz):
    print xyz
    try:
        raise RuntimeError('I going to raise exception')
    except ValueError, e:
        print e
    except RuntimeError, e:
        print e
    except Exception, e:
        print e


import unittest

class SimplisticTest(unittest.TestCase):
    def test_1(self):
        with self.assertRaises(RuntimeError):
            abc(2)

if __name__ == '__main__':
    unittest.main()



2
F
I going to raise exception
======================================================================
FAIL: test_1 (__main__.SimplisticTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/d066537/ClionProjects/pythonspark/sample.py", line 18, in test_1
    abc(2)
AssertionError: RuntimeError not raised

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

测试失败的原因以及如何纠正它。 这个有什么问题:

def abc(xyz):
    print xyz
    raise ValueError('I going to raise exception')




import unittest

class SimplisticTest(unittest.TestCase):
    def test_1(self):
        self.assertRaises(ValueError, abc(2), msg="Exception not getting caught")

if __name__ == '__main__':
    unittest.main()

2
E
======================================================================
ERROR: test_1 (__main__.SimplisticTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/d066537/ClionProjects/pythonspark/sample.py", line 12, in test_1
    self.assertRaises(ValueError, abc(2), msg="Exception not getting caught")
  File "/home/d066537/ClionProjects/pythonspark/sample.py", line 3, in abc
    raise ValueError('I going to raise exception')
ValueError: I going to raise exception

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

【问题讨论】:

  • 你提出了 RunTimeError 但在几行之后才发现它。
  • 我的第二个例子有什么问题
  • 你试图捕捉 ValueError,但它没有在任何地方引发。

标签: python python-2.7 unit-testing


【解决方案1】:

因为它不会提高它;异常在函数内部被捕获和处理。

在第二个示例中,您调用函数并将结果传递给 assertRaises,因此异常发生在 assertRaises 捕获它之前。您应该像在第一个示例中那样使用上下文管理器方法,或者传递可调用对象:self.assertRaises(ValueError, abc, 2, msg=...)

【讨论】:

  • 第二个例子有什么问题。
猜你喜欢
  • 2021-08-22
  • 2022-08-15
  • 1970-01-01
  • 2020-11-27
  • 2022-11-04
  • 1970-01-01
  • 2018-05-22
  • 2019-09-15
  • 1970-01-01
相关资源
最近更新 更多