2016-09-22 78 views
2

我不知道如何创建一个Python单元测试来检查,如果字典返回KeyError异常。我认为,单元测试会调用字典密钥,因此它看起来像这样:Python的单元测试字典断言KeyError异常

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

但是,我的测试只会出错误了KeyError异常,而不是声称一个KeyError异常发生。

+0

貌似http://stackoverflow.com/questions/11371849/testing-exception-message-with-assertraise#11371899的欺骗 –

回答

1

为了解决这个我用lambda调用词典钥匙引发错误。

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

另一种选择是使用operator.getitem

from operator import getitem 

self.assertRaises(KeyError, getitem, my_dict, 'some_key')