如何使用Mock库修补Python类
作者:互联网
我在修补课程时遇到了麻烦.我正在尝试修补属于Scrapy的东西 – 一个HtmlXpathSelector级.
这是一些代码:
from scrapy.selector import HtmlXPathSelector
from mock import MagicMock, patch
with patch('scrapy.selector.HtmlXPathSelector') as MockHtml:
instance = MockHtml.return_value
instance.method.return_value = 'foo'
example = HtmlXPathSelector()
print type(example)
assert example is instance
assert example.method == 'foo'
结果是:
<class 'scrapy.selector.lxmlsel.HtmlXPathSelector'>
Traceback (most recent call last):
File "<stdin>", line 6, in <module>
AssertionError
>>>
这个例子和Mock库教程中的例子差不多.知道为什么它不起作用吗?
解决方法:
您不应修补已在当前测试代码中导入的类.相反,您需要在相应的模块中修补该类(您想要测试).因此,如果在mymodule中导入HtmlXPathSelector,您将修补为:
with patch('mymodule.HtmlXPathSelector') as MockClass:
...
有关详细信息,请参见where to patch.
编辑如果您确实需要这个,可以使用以下方法修补当前模块中的类:
with patch('__main__.Class') as MockClass:
标签:python-mock,python,unit-testing,mocking,scrapy 来源: https://codeday.me/bug/20190725/1538399.html