假设我有这样一个函数:
def do_something(dict_obj):
# access to the dict_obj then do some stuff
eg.
if dict_obj['doors']:
do_something_with_doors()
map_car_make(dict_obj['make'])
...
if dict_obj['is_active']:
do_something_else()
我想嘲笑
dict_obj
有is_active
元素,而不关心其他元素,我该怎么做? 最佳答案
如何在Python中模拟字典是一个很好/直接的问题,其他人可以搜索,因此:
我建议MagicMock而不是模拟
过载__getitem__
from unittest.mock import MagicMock
m = MagicMock()
d = {'key_1': 'value'}
m.__getitem__.side_effect = d.__getitem__
# dict behaviour
m['key_1'] # => 'value'
m['key_2'] # => raise KeyError
# mock behaviour
m.foo(42)
m.foo.assert_called_once_with(43) # => raise AssertionError
相关问题:
How to let MagicMock behave like a dict?
Understanding __getitem__ method