我是单位测试和模拟的新手。我想将一个模拟方法附加到字典中,但我不确定如何实现这一点。我需要将键和值参数传递给append_dict
。使用这个,我得到了
SyntaxError: can't assign to function call
代码:
def mock_client(dictionary):
client = mock.MagicMock()
client.dictionary = dictionary
client.append_dictionary(key, value) = client.dictionary[key] = value #this line doesn't work
return client
在我想测试的文件中调用该函数,如下所示:
client.append_dictionary(key, value)
答案 0 :(得分:1)
您可以直接编写方法并将其设置为client
对象:
def mock_client(dictionary):
client = mock.MagicMock()
client.dictionary = dictionary
def append_dictionary(self, key, value):
self.dictionary[key] = value
client.append_dictionary = append_dictionary
return client
另一方面,如果您想测试代码中是否正确调用了append_dictionary
,那么最好这样做:
mocked_client = mock_client({})
my_code(mocked_client)
self.assertEqual(
mocked_client.append_dictionary.call_args_list,
[
mock.call("key", "value"),
]
)