2010-07-21 24 views
12

Estoy intentando probar una excepción.Problema de prueba unitaria con assertRaises

I tienen:

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

consigo el siguiente error:

====================================================================== 
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'] 

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

Gracias

Respuesta

29

self.assertRaises espera una función mro.setStatus, seguido de un número arbitrario de argumentos: en este caso, solo NEW_STATUS. self.assertRaises ensambla sus argumentos en la llamada de función mro.setStatus(NEW_STATUS) dentro de un bloque try...except, capturando y registrando así el ValueError si se produce.

Pasando mro.setStatus(NEW_STATUS) como argumento para self.assertRaises hace que el ValueError a ocurrir antes de self.assertRaises que pueden atrapar.

Así que la solución es cambiar los paréntesis de una coma:

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

que lo hizo! Gracias. :) –

+0

@Eric: No hay problema.  – unutbu

+0

Estoy usando el intérprete de python 3.3 en el IDE de pycharm. ¿Qué pasa si quiero pasar argumentos a la función bajo prueba y también incluir un mensaje en caso de que no se genere el error deseado? Ejemplo - 'self.assertRaises (ValueError, person.set_age_method, -10," Error: la edad de la persona no puede ser negativa. ")' Con esto, obtengo una excepción: 'set_age_method toma 2 argumentos posicionales pero 3 fueron dados'. Cómo puedo solucionar esto ? Por cierto, los documentos para esta afirmación no te dicen claramente cómo hacerlo. https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises. ¿Qué es ** kwds? – testerjoe2

Cuestiones relacionadas