这是我第一次尝试使用mock来模拟数据库并且无法理解它是如何工作的。
我的主要档案:
def _test( db ) :
res = {}
for x in db.getData() :
res[ x['id'] ] = x['name']
return res
这是我的测试:
def test_small() :
mock_db = mock.Mock()
mock_db.getData.return_value = [{ u'name':u'Nick',u'id':1234}]
_test( mock_db )
assert mock_db.getData.assert_called_once()
但是,断言失败了。错误是:
assert None
E + where None = <bound method Mock.assert_called_once of <Mock name='mock.getData' id='140103447969552'>>()
E + where <bound method Mock.assert_called_once of <Mock name='mock.getData' id='140103447969552'>> = <Mock name='mock.getData' id='140103447969552'>.assert_called_once
E + where <Mock name='mock.getData' id='140103447969552'> = <Mock id='140103462485712'>.getData
有人可以解释一下我错过了什么吗?理想情况下,我想稍后提出一些断言 - _test的结果是我的模拟的返回值。
答案 0 :(得分:1)
assert_called_once
方法本身already done the assertion适合您:
def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg)
你可以删除多余的assert
条款:
mock_db.getData.assert_called_once()
或
assert mock_db.getData.call_count == 1