1
我正在为python项目创建测试。正常的测试工作得很好,但是我想测试一下,如果在某种情况下我的函数会引发一个自定义的异常。为此我想使用assertRaises(Exception,Function)。有任何想法吗?测试自定义异常引发时出错(使用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>
InvalidConnectionError'的''的方法__init__'拼错如'__int__'。 – DeepSpace
谢谢你指出这一点。然而,这只是在代码错误,而不是在我的实际文件。我将编辑我的问题。 –