Python Unit Test Dictionary Assert KeyError
<p>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:</p>

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

<p>However, my test would just error out with a <strong>KeyError</strong> instead of asserting that a KeyError occurred.</p>

<p>To solve this I used a <code>lambda</code> to call the dictionary key to raise the error.</p>

<pre><code>def test_dict_keyerror_should_appear(self):
    my_dict = {'hey': 'world'}
    self.assertRaises(KeyError, lambda: my_dict['some_key'])
</code></pre>

python python-unittest