我试图模拟urllib2.urlopen库,这样我就可以为传递到函数中的不同url获得不同的响应。
我现在在我的测试文件中这样做
@patch(othermodule.urllib2.urlopen)
def mytest(self, mock_of_urllib2_urllopen):
a = Mock()
a.read.side_effect = ["response1", "response2"]
mock_of_urllib2_urlopen.return_value = a
othermodule.function_to_be_tested() #this is the function which uses urllib2.urlopen.read
我希望对othermodule.function进行测试,以便在第一次调用时获得值“response1”,在第二次调用时获得值“response2”,这就是副作用
但是othermodule.function_to_be_tested()接收
<MagicMock name='urlopen().read()' id='216621051472'>
而不是实际的反应。请告诉我哪里做错了,或者用更简单的方法。
patch
的参数需要是对象的位置的描述,而不是对象本身的描述。所以,您的问题看起来可能只是您需要将参数的字符串化为patch
。不过,为了完整起见,这里有一个完全有效的例子。首先,我们正在测试的模块:
现在,设置我们的测试:
从shell运行测试:
编辑:哎呀,最初包括了原来的错误。(正在测试以验证它是如何损坏的。)现在应该修复代码。
相关问题 更多 >
编程相关推荐