0

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'"

NicoS
  • 1
  • 2
  • `method_to_be_patched` is a name in the `bar` module imported by `foo.py`, update your source code with the required imports – rioV8 Nov 23 '20 at 15:10
  • The argument for `patch` should be a string, and as has been mentioned, `method_to_be_patched` is in `bar`. As you don't import it directly, you can just do `@patch("bar.method_to_be_patched", return_value=...)`. – MrBean Bremen Nov 25 '20 at 20:06
  • Thanks for the suggestion! I added the imports and the str in the first patch argument. I tried the suggestion ```@patch("bar.method_to_be_patched", return_value=...)```. But this does not work. It does not recognize the patch in this case. – NicoS Nov 27 '20 at 10:26

0 Answers0