[英]Passing arguments to mock method
I'm brand new to unit testing and mock. 我是单元测试和模拟的新手。 I would like to have a mock method append to a dictionary, but I'm not sure how I can accomplish this.
我想在字典中附加一个模拟方法,但是我不确定该如何完成。 I need to pass key and value arguments to
append_dict
. 我需要将键和值参数传递给
append_dict
。 Using this, I get 使用这个,我得到
SyntaxError: can't assign to function call
Code: 码:
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
The function is called in the file I want to test like so: 该函数在我要测试的文件中这样调用:
client.append_dictionary(key, value)
You could write the method directly and set it to the client
object: 您可以直接编写该方法并将其设置为
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
On the other hand, if you wish to test whether append_dictionary
is called properly in your code it may be better to do something like this: 另一方面,如果您希望测试代码中的
append_dictionary
是否被正确调用,则最好执行以下操作:
mocked_client = mock_client({})
my_code(mocked_client)
self.assertEqual(
mocked_client.append_dictionary.call_args_list,
[
mock.call("key", "value"),
]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.