简体   繁体   English

使用 unittest.mock.patch 全局模拟方法

[英]Mock method globally with unittest.mock.patch

I'm trying to mock a method that is called by another method in a separate module.我正在尝试模拟一个由单独模块中的另一个方法调用的方法。 Specifically, I would like the call to foo in bar.py to be replaced with a call to mock_foo :具体来说,我希望将 bar.py 中对foo的调用替换为对mock_foo的调用:

foo.py foo.py

def foo():
    return 'foo'

bar.py酒吧.py

from foo import foo

def bar.py():
    return foo()

test.py测试.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'

The patch approach above doesn't work.上面的patch方法不起作用。 Is this possible to do with the mock library?这可能与模拟库有关吗? If so, how should I modify test.py?如果是这样,我应该如何修改test.py?

You should patch the foo function imported inside bar module.您应该修补导入 inside bar模块的foo function。 So, the target should be bar.foo .所以,目标应该是bar.foo

Eg例如

foo.py : foo.py

def foo():
    return 'foo'

bar.py : bar.py

from foo import foo


def bar():
    return foo()

test_bar.py : 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()

unit test result:单元测试结果:

⚡  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%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM