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

2024-04-25 07:45:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个python项目创建测试。正常的测试工作得很好,但是我想测试在特定条件下我的函数是否引发了自定义的异常。因此,我想使用assertRaises(异常,函数)。有什么想法吗?你知道吗

引发异常的函数是:

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>

Tags: 函数testselfstringdefconnectclassraise
1条回答
网友
1楼 · 发布于 2024-04-25 07:45:25

assertRaises期望实际perform the call。但是,您已经自己执行了,因此在assertRaises实际执行之前抛出错误。他说

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

请使用以下任一选项:

self.assertRaises(e.InvalidConnectionError, c.connect, comp, comp)

with self.assertRaises(e.InvalidConnectionError):
    c.connect(comp, comp)

相关问题 更多 >

    热门问题