我有以下测试代码检查函数中引发的异常。我希望测试能够通过,但会显示失败。这是测试代码:
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()
在other.func()
assert 语句中调用时,MyException
会引发(可以轻松检查)。所以,assertRaises
测试应该通过测试,因为other.func()
失败MyException
,但是:
....
MyException: 'ERROR: Just raised my exception!'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
我看不出有什么问题,所以我希望能就这个问题提供一些意见。