我有以下测试代码检查函数中的异常引发.我希望测试通过,但是会指示失败.这是测试代码:
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()
Run Code Online (Sandbox Code Playgroud)
当other.func()被调用的断言语句,MyException提高(可以容易地检查).因此,assertRaises测试应该通过测试,因为other.func()与...相关MyException,但是:
....
MyException: 'ERROR: Just raised my exception!'
----------------------------------------------------------------------
Ran 1 test …Run Code Online (Sandbox Code Playgroud)