Using assert raise within tests is a tricky thing - So today I'll focus on how to properly use it :)
S0-E11/E30 :)
Unittest with self.assertRaise for function tests
Let's present example for function:
import unittest
def raiser_function():
print "Is This function Called?"
raise NotImplementedError()
class TestCase2(unittest.TestCase):
def test_will_pass_self_assert_raise(self):
# proper usage
self.assertRaises(NotImplementedError, raiser_function)
def test_with_self_assert_raise(self):
# proper usage
with self.assertRaises(NotImplementedError):
raiser_function()
def test_will_fail(self):
# added intentionally this line below for the test not to fail.
with self.assertRaises(NotImplementedError):
# you should not call methoc/function inside of self.assertRaises, but give arguments and kwargs as self.assertRaises argument
self.assertRaises(NotImplementedError, raiser_function())
if __name__ == "__main__":
unittest.main()
Unittest with self.assertRaise for object method tests
Let's present example for object-method:
import unittest
class RaiserClass(object):
def methodToRaiseNotImplementedError(self):
print "Is This Test Called?"
raise NotImplementedError()
class TestCase1(unittest.TestCase):
def test_will_pass_self_assert_raise(self):
self.assertRaises(NotImplementedError, RaiserClass().methodToRaiseNotImplementedError)
def test_with_self_assert_raise(self):
with self.assertRaises(NotImplementedError):
RaiserClass().methodToRaiseNotImplementedError()
def test_will_fail(self):
# added intentionally this line below for the test not to fail.
with self.assertRaises(NotImplementedError):
raiser_object = RaiserClass()
self.assertRaises(NotImplementedError, raiser_object.methodToRaiseNotImplementedError())
def test_will_fail2(self):
# added intentionally this line below for the test not to fail.
with self.assertRaises(NotImplementedError):
self.assertRaises(NotImplementedError, RaiserClass().methodToRaiseNotImplementedError())
if __name__ == "__main__":
unittest.main()
Acknowledgements
- How to properly use unit-testing's assertRaises() with NoneType objects?
- Careful with your assertRaises() and inheritance of exceptions
Thanks!
That's it :) Comment, share or don't :)
If you have any suggestions what I should blog about in the next articles - please give me a hint :)
See you tomorrow! Cheers!
Comments
comments powered by Disqus