简体   繁体   中英

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 :

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'

The patch approach above doesn't work. Is this possible to do with the mock library? If so, how should I modify test.py?

You should patch the foo function imported inside bar module. So, the target should be bar.foo .

Eg

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()

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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