5

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
  • 10,736
  • 9
  • 66
  • 73
  • 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

4

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
  • 10,736
  • 9
  • 66
  • 73
1

Another option would be to use operator.getitem:

from operator import getitem

self.assertRaises(KeyError, getitem, my_dict, 'some_key')
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148