How can I test an exception in my code with unittest?

1

I'm studying some of Python's unittest and I've packed it. In my code the user must enter a valid value, if an invalid value occurs it should fall into the exception, but how can I test this? My code looks like this:

if moeda not in (2, 5, 10, 20, 50, 100):
   raise Exception('Valor de moeda invalido.')
...
    
asked by anonymous 19.12.2016 / 08:01

1 answer

0

You should use TestCase.assertRaises :

import unittest

class SeusTestes(unittest.TestCase):
    def testa_excecao(self):
        self.assertRaises(SuaException, objeto.suaFuncao)

if __name__ == '__main__':
    unittest.main()
    
19.12.2016 / 11:46