6

I wasn't sure how to create a Python unittest to check if a dictionary returned a KeyError. I thought the unit test would call the dictionary key so it would look like this:

def test_dict_keyerror_should_appear(self):
    my_dict = {'hey': 'world'}
    self.assertRaises(KeyError, my_dict['some_key'])

However, my test would just error out with a KeyError instead of asserting that a KeyError occurred.

Will
  • 11,276
  • 9
  • 68
  • 76
  • Looks like a dupe of http://stackoverflow.com/questions/11371849/testing-exception-message-with-assertraise#11371899 – Xavier C. Sep 22 '16 at 13:32

2 Answers2

6

To solve this I used a lambda to call the dictionary key to raise the error.

def test_dict_keyerror_should_appear(self):
    my_dict = {'hey': 'world'}
    self.assertRaises(KeyError, lambda: my_dict['some_key'])
Will
  • 11,276
  • 9
  • 68
  • 76
2

Another option would be to use operator.getitem:

from operator import getitem

self.assertRaises(KeyError, getitem, my_dict, 'some_key')
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195