gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:55 24 4
gpt4 key购买 nike

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

引发异常的函数是:

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

异常(exception)情况是:

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>

最佳答案

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)

关于python - 测试自定义异常的引发时出错(使用 assertRaises()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com