我一直在阅读python嘲笑,但无法理解以下代码为何失败。
我有两个班,Potato
和一个PotatoBag
像下面这样。Figure
存储在中food.py
,Report
并存储在中bag.py
。
class Potato:
def create_potato(self):
pass
def output_potato(self):
pass
class PotatoBag:
def __init__(self, potatoes):
self.potatoes = potatoes
def output_to_file(self):
for fig in self.potatoes:
fig.create_potato()
fig.output_potato()
目前,我正在尝试对输出方法进行单元测试,以使Report能够正确地调用create_figure
并output_figure
通过模拟从Figure中调用。这是我的测试代码:
from unittest.mock import MagicMock, patch
from bag import PotatoBag
from food import Potato
import pytest
@pytest.fixture(scope='module')
def potatoes():
x = Potato()
y = Potato()
return [x, y]
@patch('food.Potato')
def test_output_to_file(mock_potato, potatoes):
test_potato_bag = PotatoBag(potatoes)
test_potato_bag.output_to_file()
mock_potato.return_value.create_potato.assert_called()
mock_potato.return_value.output_potato.assert_called()
pytest立即产生一个AssertionError
声明,从未调用过create_figure。
_mock_self = <MagicMock name='Potato().create_potato' id='140480853451272'>
def assert_called(_mock_self):
"""assert that the mock was called at least once
"""
self = _mock_self
if self.call_count == 0:
msg = ("Expected '%s' to have been called." %
self._mock_name or 'mock')
> raise AssertionError(msg)
E AssertionError: Expected 'create_potato' to have been called.
/home/anaconda3/lib/python3.7/unittest/mock.py:792: AssertionError
我的代码有什么问题?
您正在传递灯具中Report
的清单,Figures
而不是模拟清单。
将测试更改为...
@patch('figure.Figure')
def test_output_to_file(mock_figure, figures):
test_report = Report([mock_figure])
test_report.output_to_file()
mock_figure.create_figure.assert_called_once()
mock_figure.output_figure.assert_called_once()
这解决了output_to_file
正确调用函数的测试,Figure
而无需真正担心设置图形并处理调用这些函数可能带来的任何副作用或其他复杂性。可以为Figure
;)的单元测试省去烦恼
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句