Question
Asked By – Andriusa
I did a simple test case:
def setUp(self):
self.testListNone = None
def testListSlicing(self):
self.assertRaises(TypeError, self.testListNone[:1])
and I am expecting test to pass, but I am getting exception:
Traceback (most recent call last):
self.assertRaises(TypeError, self.testListNone[:1])
TypeError: 'NoneType' object is unsubscriptable
I thought that assertRaises will pass since TypeError exception will
be raised?
Now we will see solution for issue: How to properly use unit-testing’s assertRaises() with NoneType objects? [duplicate]
Answer
If you are using python2.7 or above you can use the ability of assertRaises to be use as a context manager and do:
with self.assertRaises(TypeError):
self.testListNone[:1]
If you are using python2.6 another way beside the one given until now is to use unittest2 which is a back port of unittest new feature to python2.6, and you can make it work using the code above.
N.B: I’m a big fan of the new feature (SkipTest, test discovery …) of unittest so I intend to use unittest2 as much as I can. I advise to do the same because there is a lot more than what unittest come with in python2.6 <.
This question is answered By – mouad
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0