我正在使用 Python 2.6.6
我想要做的是用 Mock 替换对象的创建,以确保进行正确的调用。应该直截了当。
我的模块:
import dir.SubModule
class Cls( object ):
def Start( self ):
self.__obj = dir.SubModule.SubCls()
self.__obj.foo()
我的测试:
import MyModule
import unittest
from mock import Mock, MagicMock, patch
class MyTest( unittest.TestCase ):
def setUp( self ):
self.uut = MyModule.Cls()
def test_one( self ):
with patch( 'dir.SubModule.SubCls', spec=True ) as mockObj:
print "mock calls before"
print mockObj.mock_calls
self.uut.Start()
print "called: " + str( mockObj.called )
print "foo called: " + str( mockObj.foo.called )
print "call_count: " + str( mockObj.call_count )
print "call_args: " + str( mockObj.call_args )
print "args_list: " + str( mockObj.call_args_list )
print "mock calls:\n" + str( mockObj.mock_calls )
print "method calls:\n " + str( mockObj.method_calls )
输出是:
mock calls before:
[]
called: True
foo called: False
call_count: 1
call_args: call()
args_list: [call()]
mock calls:
[call(), call().foo()]
method calls:
[]
然而测试失败了:
AssertionError: Expected call: foo()
Not called
我不明白模拟是如何报告调用的,但我不能断言它们被调用了。我错过了什么?
编辑:在添加了所有指标的报告之后,我似乎对 python 模拟有一些基本的误解。如果 foo() 在调用列表中,那么为什么调用计数只有 1,为什么 foo.call 报告 'False'?