【发布时间】:2018-07-10 13:05:09
【问题描述】:
我正在尝试模拟一个列表类型的全局变量。
下面是插图——
这是 first_main.py -
url=[] -- url.append(hello.replace(-test','')) 的结果被存储在 method_a() 中,这是全局变量
def method_a():
url.append(hello.replace(-test',''))
return something
现在,url=[] 用于另一种方法。
def method_b():
*Some codes and url=[] is used here in this code.*
print url
return True
现在,我正在测试method_b -
@mock.patch('first_main.url')
def test_method_b(self, mock_url_list):
mock_url_list.return_value.url.return_value = [['a','b'],['c','d']]
reponse = method_b()
print response
现在,如果我在 method_b 中使用的 url 打印语句,它应该返回 [['a','b'],['c','d']] 而不是 id。
------------控制台------------
MagicMock name='url' id='090909090'
我想在列表中返回类型,即。 [['a','b'],['c','d']] 而不是 id。
谢谢
如果需要澄清,请告诉我。
【问题讨论】:
-
用
@mock.patch('first_main.url'),改成mock_url_list.return_value=[['a','b'],['c','d']],然后你可以在method_b里面调用method_a()获取url_list。 -
请忽略调用
method_a部分,我在想你提到的另一篇文章。 -
:D 你的意思是“然后你可以在 method_b 中调用 method_a() 来获取 url_list”? method_a() 返回类型不是 url。那么,我怎样才能得到这个全局 url 值呢?你的意思是我应该先运行 method_a() 然后运行我正在尝试测试的实际 method_b /
-
@mock.path.('first_main.url,它会在你修补的任何方法的范围内模拟模块first_main中的url,它可以是a或b,只是你提到的代码是method_b。如果要测试 mothod_a,请在 test_method_a() 中对其进行修补 -
好的。所以在我的测试方法下,我调用了method_a(),它返回了响应[['a','b'],['c','d']]。但是当我调用实际测试方法的 method_b() 时,会出现 url 的打印语句。在这里,它应该打印 [['a','b'],['c','d']]。但它正在返回我的问题中提到的 id 。我错过了什么吗?
标签: python unit-testing mocking python-unittest