我试图以一种方式模拟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
Run Code Online (Sandbox Code Playgroud)
我希望othermodule.function_to_be_tested在第一次调用时获得值"response1",在第二次调用时获得"response2",这是side_effect将执行的操作
但是othermodule.function_to_be_tested()收到了
<MagicMock name='urlopen().read()' id='216621051472'>
Run Code Online (Sandbox Code Playgroud)
而不是实际的反应.请告诉我出错的地方或更简单的方法.