可能重複:
How do you test that a Python function throws an exception?如何測試拋出異常
我要做的白盒和黑盒測試所以我真的不知道它是如何可能測試一個導致異常的函數,像這樣一個
class validator_client():
def validate_client(self,client):
erori=[]
if client.get_identitate()=="":
erori.append("Nu exista ID!")
if client.get_nume()=="":
erori.append("Nu exista nume!")
if (client.get_filme_inchiriate()!="da") and (client.get_filme_inchiriate()!="nu") :
erori.append("Campul 'Filme inchiriate' completat gresit!")
if len(erori)>0:
raise ValidatorException(erori)
我已經讀了一些關於assertRises()但我不能用這種方法導入模塊,在stackowerflow上發現這個:
from testcase import TestCase
import mymod
class MyTestCase(TestCase):
def test1(self):
self.assertRaisesWithMessage(SomeCoolException,
'expected message',
mymod.myfunc)
但是我不能使它工作。
你想要什麼結果?你想創建一個引發異常的函數嗎?只是這樣做。你想抓住它嗎?使用try-except塊。你想要別的嗎?讓自己更清楚。 –
好吧,我必須測試該函數的所有分支,例如,我該如何斷言或者類似於客戶端沒有得到「身份」的東西,我希望能夠期待它,並將其置於類似assertRises的測試中(「Nu exista ID!」,validate_client) – JackRobinson
這對我來說還不完全清楚。你想測試一個對象是否有可召喚的成員?你可以用'if hasattr(obj,'membername')和callable(obj.membername)'來檢查。您建議函數引發異常是一個問題。它有什麼問題? –