>>> int(Mock())
TypeError: int() argument must be a string or a number, not 'Mock'
>>> int(MagicMock())
1
>>> len(Mock())
TypeError: object of type 'Mock' has no len()
>>> len(MagicMock())
0
这些可能不是很直观(至少对我来说不是很直观):
>>> with MagicMock():
... print 'hello world'
...
hello world
>>> MagicMock()[1]
<MagicMock name='mock.__getitem__()' id='4385349968'>
In [1]: from unittest.mock import Mock, MagicMock, ANY
In [2]: mock = Mock()
In [3]: magic = MagicMock()
In [4]: mock.foo == ANY
Out[4]: True
In [5]: magic.foo == ANY
Out[5]: False
比较ANY可能是有用的,例如,比较两个字典之间的几乎每个键,其中一些值是使用mock计算的。
如果你使用Mock,这将是有效的:
self.assertDictEqual(my_dict, {
'hello': 'world',
'another': ANY
})