相关疑难解决方法(0)

assertRaises失败,即使是callable引发了所需的异常(python,unitest)

我有以下测试代码检查函数中的异常引发.我希望测试通过,但是会指示失败.这是测试代码:

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)

python unit-testing

11
推荐指数
2
解决办法
4522
查看次数

标签 统计

python ×1

unit-testing ×1