Is it possible to mock a return value of a function which is called within a function which again is used in another method? I know it is a very complicated structure. I would like the mocked method to return a specific value. The following example shows the structure:
#foo.py
from bar import other_method
class Foo:
def method_1():
results = other_method()
#bar.py
def method_to_be_patched():
return 'abc'
def other_method():
res = method_to_be_patched()
...
return 'result'
I would like to test method_1
and patch the method_to_be_patched
. I read a related issue (Using python's mock patch.object to change the return value of a method called within another method) and tried the following
#test.py
from unittest import TestCase
from unittest.mock import patch
from foo import Foo
patch_value = '123'
class Test(TestCase):
def setUp(self):
self.foo = Foo()
@patch('Foo.other_method.method_to_be_patched', return_value = patch_value)
def test_method_1(mocked_method):
self.foo.method_1()
I would expect that the patch would return the patched value at the point where method_to_be_patched
is called within self.foo.method_1()
. But the interpreter displays the error message "function other_method at ... does not have the attribute 'method_to_be_patched'"