我有以下結構:
sources/
- parser/
- sources_parser.py # SourcesParser class is here
- tests/
- test_sources_parsers.py # SourcesParserTest is here
sources_parser.py:
from sources.parser.sitemap_parser import SitemapParser
class SourcesParser(object):
__sitemap_parser: SitemapParser
def __init__(self) -> None:
super().__init__()
self.__sitemap_parser = SitemapParser()
def parse(self):
# ...
urls = self.__parse(source)
self.logger.info(f'Got {len(urls)} URLs')
def __parse(self, source: NewsSource) -> List[str]:
results = self.__sitemap_parser.parse_sitemap(source.url)
self.logger.info(f'Results: {results}, is list: {isinstance(results, list)}')
return results
測驗:
class SourcesParserTest(TestCase):
@patch('sources.parser.sources_parser.SitemapParser')
def test_normal_parse(self, mock_sitemap_parser):
mock_sitemap_parser.parse_sitemap.return_value = [
'https://localhost/news/1',
'https://localhost/news/2',
'https://localhost/news/3',
]
parser = SourcesParser()
parser.parse()
日志是:
Results: <MagicMock name='SitemapParser().parse_sitemap()' id='5105954240'>, is list: False
Got 0 URLs
如果我正確理解模擬,parse_sitemap呼叫應該回傳給定的 URL 串列,而是回傳一個Mock轉換為空串列的物件。
Python 版本是 3.9。
怎么了?
uj5u.com熱心網友回復:
如果模擬成員函式,則必須模擬模擬實體物件上的函式,而不是模擬類物件上的函式。這可能并不完全直觀,因為成員函式屬于一個類,但您可以將其視為系結方法與未系結方法——您必須模擬系結方法。
使用Mock,模擬實體是通過return_value在類物件上使用來完成的,類似于模擬函式呼叫的結果,因此在您的情況下,您需要:
@patch('sources.parser.sources_parser.SitemapParser')
def test_normal_parse(self, mock_sitemap_parser):
mocked_parser = mock_sitemap_parser.return_value # mocked instance
mock_parser.parse_sitemap.return_value = [
'https://localhost/news/1',
'https://localhost/news/2',
'https://localhost/news/3',
]
...
(拆分模擬僅用于說明)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/324868.html
標籤:Python 蟒蛇-3.x 单元测试 python-unittest 蟒蛇模拟
上一篇:VisualStudio中的SQLServerUnitTesting-DROPDATABASE[MyDb]
下一篇:角度單元測驗無法讀取未定義的屬性
