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

Asked

Viewed 149 times

1

I am studying a little of Python’s unittest and I have stopped there. In my code the user must enter a valid value, if an invalid value occurs should fall in Exception, however how can I test it ? My code is as follows::

if moeda not in (2, 5, 10, 20, 50, 100):
   raise Exception('Valor de moeda invalido.')
...

1 answer

0


You must use Testcase.assertRaises:

import unittest

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

if __name__ == '__main__':
    unittest.main()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.