2010-07-21 19 views
12

Sto provando a verificare un'eccezione.Test unità Problema con assertRaises

ho:

def test_set_catch_status_exception(self): 
    mro = self.mro 
    NEW_STATUS = 'No such status' 
    self.assertRaises(ValueError,mro.setStatus(NEW_STATUS)) 

ottengo il seguente errore:

====================================================================== 
ERROR: test_set_catch_status_exception (__main__.TestManagementReviewGoalGetters) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "test_ManagementReviewObjective.py", line 68, in test_set_catch_status_exception 
    self.assertRaises(ValueError,mro.setStatus(NEW_STATUS)) 
    File "/Users/eric/Dropbox/ManagementReview.py", line 277, in setStatus 
    raise ValueError('%s is not in the list of allowed statuses: %s' % (status,LIST_OF_STATUSES)) 
ValueError: No such status is not in the list of allowed statuses: ['Concern or Delay', 'On Track', 'Off Track/Needs Attention'] 

---------------------------------------------------------------------- 

Grazie

risposta

29

self.assertRaises prevede una funzione mro.setStatus, seguita da un numero arbitrario di argomenti: in questo caso, solo NEW_STATUS. self.assertRaises assembla i suoi argomenti nella chiamata di funzione mro.setStatus(NEW_STATUS) all'interno di un blocco try...except, catturando e registrando quindi lo ValueError se si verifica.

Passando mro.setStatus(NEW_STATUS) come argomento self.assertRaises provoca l'ValueError che si verifichi prima self.assertRaises può intrappolare esso.

Quindi la correzione è quello di cambiare le parentesi di una virgola:

self.assertRaises(ValueError,mro.setStatus,NEW_STATUS) 
+0

Che lo ha fatto! Grazie. :) –

+0

@Eric: Nessun problema.  – unutbu

+0

Sto usando l'interprete python 3.3 in IDP pycharm. Cosa succede se voglio passare argomenti alla funzione sotto test e includere anche un messaggio nel caso in cui l'errore desiderato non venga generato? Esempio - 'self.assertRaises (ValueError, person.set_age_method, -10," Errore: L'età della persona non può essere negativa. ")' Con questo, ottengo un'eccezione: 'set_age_method prende 2 argomenti posizionali ma 3 sono stati dati'. Come posso risolvere questo? A proposito, i documenti per questa asserzione non ti dicono chiaramente come farlo. https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises. Cosa è ** kwds? – testerjoe2