测试自定义异常的引发时出错(使用assertRaises())

时间:2016-07-28 10:06:19

标签: python exception

我正在为python项目创建测试。正常的测试工作正常,但我想测试在某种情况下我的函数是否会引发一个自定义的异常。因此我想使用assertRaises(Exception,Function)。有什么想法吗?

引发异常的函数是:

def connect(comp1, comp2):
    if comp1 == comp2:
        raise e.InvalidConnectionError(comp1, comp2)
    ...

例外是:

class InvalidConnectionError(Exception):
    def __init__(self, connection1, connection2):
        self._connection1 = connection1
        self._connection2 = connection2

    def __str__(self):
        string = '...'
        return string

测试方法如下:

class TestConnections(u.TestCase):
    def test_connect_error(self):
        comp = c.PowerConsumer('Bus', True, 1000)
        self.assertRaises(e.InvalidConnectionError, c.connect(comp, comp))

但是我收到以下错误:

Error
Traceback (most recent call last):
File "C:\Users\t5ycxK\PycharmProjects\ElectricPowerDesign\test_component.py", line 190, in test_connect_error
self.assertRaises(e.InvalidConnectionError, c.connect(comp, comp))
File "C:\Users\t5ycxK\PycharmProjects\ElectricPowerDesign\component.py", line 428, in connect
raise e.InvalidConnectionError(comp1, comp2)
InvalidConnectionError: <unprintable InvalidConnectionError object>

1 个答案:

答案 0 :(得分:6)

{_method:'put', order: order_data }预计实际上perform the call。但是,您已经自己执行了它,从而在assertRaises实际执行之前抛出错误。

assertRaises

改为使用其中任何一个:

self.assertRaises(e.InvalidConnectionError, c.connect(comp, comp))
# run this ^ with first static argument ^ and second argument ^ from `c.connect(comp, comp)`