我正在为此版本使用Python2.7和模块unittest
和mock
。我有一种情况,我想模拟类实例及其返回值的函数调用。麻烦的是,该实例是另一个类的实例的成员。让我用代码澄清一下。
假设我在Bin
中定义了一个类my_package/bin.py
:
class Bin():
def __init__(self):
# code to initialize other stuff
self.rubbish = self.fill_with_rubbish() # creates list of rubbish instances
def inspect_rubbish(self):
inspection_results = []
for rubbish in self.rubbish:
inspection_results.append(rubbish.inspect())
我在Rubbish
中也定义了类my_package/rubbish.py
:
class Rubbish():
def __init__(self):
# initialization stuff
def inspect(self):
return 'Nice rubbish'
现在,在我的/tests
文件夹中,有一个测试文件test_bin.py
,在其中设置环境并按如下所示导入垃圾箱和垃圾:
import my_package.bin as _bin
import my_package.rubbish as _rubbish
并且我正在尝试测试inspect_rubbish()
类的Bin
。上面的代码显然不是我的生产代码,但是在我的原始代码中,我希望能够修改inspect
的{{1}}的重整值并执行各种Rubbish
调用它以检查它被调用了多少次,等等。
我一直被困在如何实际模拟Bin实例的Rubbish实例的方法上。我试图通过一些补丁解决问题,但无济于事。
assert
但是此代码以def test_inspect_rubbish(self):
with patch('my_package.bin.Bin', autospec=True) as mock_bin, \
patch.object('my_package.rubbish.Rubbish.inspect') as mock_inspect:
mock_inspect.return_value = 'Bad rubbish'
bin = _bin.Bin()
bin.rubbish = [MagicMock(), MagicMock()]
result = bin.inspect_rubbish()
mock_inspect.assert_called()
失败,因此我想它根本没有达到我的预期。我该如何模拟这种行为,然后对其进行断言?
答案 0 :(得分:2)
Bin
,所以bin.inspect_rubbish()
是一个模拟呼叫,它什么都不做。bin.rubbish = [MagicMock(), MagicMock()]
意味着永远不会调用模拟的Rubbish.inspect
,对于每个模拟都只会调用MagicMock().inspect
。此代码有效:
def test_inspect_rubbish(self):
with patch('my_package.rubbish.Rubbish.inspect') as mock_inspect:
mock_inspect.return_value = 'Bad rubbish'
bin = _bin.Bin()
bin.rubbish = [_rubbish.Rubbish(), _rubbish.Rubbish()]
result = bin.inspect_rubbish()
mock_inspect.assert_called()
演示:https://repl.it/repls/RundownTastyKernel
我也将patch.object
更改为patch
,因为这样会导致错误。