2016-07-28 10 views
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> 
+1

InvalidConnectionError' 'の' __init__'方法は__int__' 'として間違っています。 – DeepSpace

+0

ありがとうございます。しかし、実際のファイルではなく、ここのコードでは間違っていました。私は私の質問を編集します。 –

答えて

5

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) 
+0

ありがとう、これは問題を解決しました。私はあなたの答えを受け入れた! –

関連する問題