我有以下测试代码检查函数中引发的异常。我希望测试能够通过,但是却显示失败。这是测试代码:
import unittest
# define a user-defined exception
class MyException(Exception):
def __str__(self):
return repr("ERROR: Just raised my exception!")
# this is my main class with a method raising this exception
class MyMainObject(object):
def func(self):
raise MyException()
# the test class
class TestConfig(unittest.TestCase):
def test_1(self):
other = MyMainObject()
self.assertRaises(MyException, other.func())
# calling the test
if __name__ == '__main__':
unittest.main()
When other.func()
在断言语句中调用,MyException
被提升(可以轻松检查)。所以assertRaises
测试应该通过测试,因为other.func()
失败了MyException
, BUT:
....
MyException: 'ERROR: Just raised my exception!'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
我没有看到任何问题,所以我希望能就这个问题提供一些意见。
assertRaises
为您调用该函数。通过自己调用,会引发异常before assertRaises
可以测试一下。
将您的代码更改为:
self.assertRaises(MyException, other.func)
它会正常工作。或者,您可以使用assertRaises
作为上下文管理器(python 2.7 及更高版本):
with self.assertRaises(MyException):
other.func()
Using assertRaises
作为上下文管理器,您现在可以检索异常实例并对其执行进一步的测试:
with self.assertRaises(MyException) as raises_cm:
other.func()
exception = raises_cm.exception
self.assertEqual(exception.args, ('foo', 'bar'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)