【发布时间】:2016-03-01 01:35:14
【问题描述】:
如果我有两个包含以下内容的文件:
test_helper.py:
class Installer:
def __init__(self, foo, bar, version):
# Init stuff
raise Exception('If we're here, mock didn't work')
def __enter__(self):
return self
def __exit__(self, type, value, tb):
# cleanup
pass
def install(self):
# Install stuff
raise Exception('If we're here, mock didn't work')
并且
test.py:
import unittest
from mock import patch
from test_helper import Installer
class Deployer:
def deploy(self):
with Installer('foo', 'bar', 1) as installer:
installer.install()
class DeployerTest(unittest.TestCase):
@patch('tests.test_helper.Installer', autospec=True)
def testInstaller(self, mock_installer):
deployer = Deployer()
deployer.deploy()
mock_installer.assert_called_once_with('foo', 'bar', 1)
上面的代码没有正确测试。模拟未正确应用:
File "/Library/Python/2.7/site-packages/mock-1.3.0-py2.7.egg/mock/mock.py", line 947, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'Installer' to be called once. Called 0 times.
如果我在test.py 中进行以下更改:
- 将
from test_helper import Installer更改为import test_helper,然后 - 将
with Installer('foo', 'bar', 1) as installer:更改为with test_helper.Installer('foo', 'bar', 1) as installer:
然后代码就可以工作了。为什么模拟仅在我使用完全限定名称时适用?它应该在部分合格的情况下工作吗?
【问题讨论】:
标签: python unit-testing mocking python-unittest