Source From Here
Question
How does one write a unittest that fails only if a function doesn't throw an expected exception?
How-To
Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example:
- TestExp.py
Running example:
Question
How does one write a unittest that fails only if a function doesn't throw an expected exception?
How-To
Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example:
- TestExp.py
- #!/usr/bin/env python3
- import unittest
- def my_fun(val):
- if val % 2 == 0:
- raise Exception('Val is even')
- else:
- return "Val is odd"
- class MyTestCase(unittest.TestCase):
- def test_01(self):
- self.assertEquals("Val is odd", my_fun(1))
- def test_02(self):
- # Even number will raise Exception
- self.assertRaises(Exception, my_fun, 2)
- # You can leverage with this way
- with self.assertRaises(Exception) as context:
- my_fun(4)
- self.assertTrue('Val is even' in str(context.exception))
沒有留言:
張貼留言