大多数关于 Python 模拟的建议都包含在单元测试框架之外的简短片段中。这个工作发现,我正在尝试遵循这个建议,但是一旦我将它嵌入到适当的单元测试中,它就不会成功。例如,这段代码在最后的注释中产生输出:
# foo.py
def some_fn():
return 'some_fn'
class Foo( object ):
def method_1( self ):
return some_fn()
# bar.py (depends on foo.py)
import foo
class Bar( object ):
def method_2( self ):
tmp = foo.Foo()
return tmp.method_1()
# test.py (tests bar.py)
import unittest
import bar
from mock import patch
class Test( unittest.TestCase ):
def setUp( self ):
pass
def tearDown( self ):
pass
@patch( 'foo.some_fn' )
def test_bar( self, mock_some_fn ):
mock_some_fn.return_value = 'test-val-1'
tmp = bar.Bar()
print tmp.method_2()
self.assertEqual( tmp.method_2(), 'test-val-1' ) # line 32
mock_some_fn.return_value = 'test-val-2'
self.assertEqual( tmp.method_2(), 'test-val-2' )
if __name__ == "__main__":
unittest.main()
我在 PyDev 中运行并查看:
Finding files... done.
Importing test modules ... done.
some_fn
======================================================================
FAIL: test_bar (test.foo.all.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/mock.py", line 1201, in patched
return func(*args, **keywargs)
File "/home/russ/dev/workspace/python-mocking/test/foo/all.py", line 32, in test_bar
self.assertEqual( tmp.method_2(), 'test-val-1' )
AssertionError: 'some_fn' != 'test-val-1'
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)
删除单元测试框架,这段代码运行良好(这里,只是整个文件的test.py部分):
...
# test.py (tests bar.py)
import bar
from mock import patch
@patch( 'foo.some_fn' )
def test_bar( mock_some_fn ):
mock_some_fn.return_value = 'test-val-1'
tmp = bar.Bar()
print tmp.method_2()
assert tmp.method_2() == 'test-val-1'
mock_some_fn.return_value = 'test-val-2'
assert tmp.method_2() == 'test-val-2'
运行时成功产生:
~/dev/workspace/python-mocking/test/foo $ python
Python 2.7.5 (default, Nov 3 2014, 14:26:24)
...
>>> import all0
>>> all0.test_bar()
test-val-1
我还必须做些什么才能使其在单元测试框架中运行?