assertRaises 失败,即使是可调用的也会引发所需的异常(python、unitest) [英] assertRaises fails, even the callable raises the required exception (python, unitest)

查看:19
本文介绍了assertRaises 失败,即使是可调用的也会引发所需的异常(python、unitest)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following test-code checking for an exception raising in a function. I expect the test to pass, but a failure is indicated instead. Here is the test code:

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()

当在 assert 语句中调用 other.func() 时,会引发 MyException(可以轻松检查).因此,assertRaises 测试应该通过测试,因为 other.func()MyException 而失败,但是:

When other.func() is called in the assert statement, MyException is raised (can be checked easily). So, the assertRaises test should pass the test, as other.func() failes with MyException, BUT:

....
MyException: 'ERROR: Just raised my exception!'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)

我没有发现有什么问题,所以我希望能就此问题提供一些意见.

I do not see something wrong, so I would appreciate some input on this problem.

推荐答案

assertRaises 为您调用函数.通过自己调用它, assertRaises 可以测试它之前引发异常.

assertRaises calls the function for you. By calling it yourself, the exception is raised before assertRaises can test it.

将您的代码更改为:

self.assertRaises(MyException, other.func)

它会正常工作.或者,您可以使用 assertRaises 作为上下文管理器(python 2.7 及更高版本):

and it'll work correctly. Alternatively, you can use assertRaises as a context manager (python 2.7 and up):

with self.assertRaises(MyException):
    other.func()

使用 assertRaises 作为上下文管理器具有额外的优势,您现在可以检索异常实例并对其执行进一步测试:

Using assertRaises as a context manager has the added advantage that you can now retrieve the exception instance and perform further tests on it:

with self.assertRaises(MyException) as raises_cm:
    other.func()

exception = raises_cm.exception
self.assertEqual(exception.args, ('foo', 'bar'))

这篇关于assertRaises 失败,即使是可调用的也会引发所需的异常(python、unitest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆