我试图模拟由另一个模块中的另一个方法调用的方法。具体来说,我希望将bar.py中对foo
的调用替换为对mock_foo
的调用:
foo.py
def foo():
return 'foo'
bar.py
from foo import foo
def bar.py():
return foo()
test.py
from bar import bar
def mock_foo():
return 'mock_foo'
def testmethod():
with patch('foo.foo', mock_foo):
print(bar())
# Expected output:'mock_foo'
上面的patch
方法不起作用。这可以用模拟库做到吗?如果是,我应该如何修改test.py?
应该修补在bar
模块内导入的foo
函数。所以,目标应该是bar.foo
。
。
foo.py
:
def foo():
return 'foo'
bar.py
:
from foo import foo
def bar():
return foo()
test_bar.py
:
from bar import bar
import unittest
from unittest.mock import patch
def mock_foo():
return 'mock_foo'
class BarTest(unittest.TestCase):
def test_bar(self):
with patch('bar.foo', mock_foo):
print(bar())
self.assertEqual(bar(), 'mock_foo')
if __name__ == '__main__':
unittest.main()
单元测试结果:
⚡ coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/66540831/test_bar.py && coverage report -m --include './src/**'
mock_foo
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Name Stmts Miss Cover Missing
----------------------------------------------------------------------
src/stackoverflow/66540831/bar.py 3 0 100%
src/stackoverflow/66540831/foo.py 2 1 50% 2
src/stackoverflow/66540831/test_bar.py 12 0 100%
----------------------------------------------------------------------
TOTAL 17 1 94%