8

what I currently have is:

def some_method():
    some_obj = some_other_method()
    # This is what I want to mock return value of:
    some_obj.some_obj_some_method()

@patch('some_package.some_other_method')
def test_some_stuff(some_other_method_patch):
    some_other_method_patch.return_value = SomeObject()

How could I get about setting some_obj.some_obj_some_method() return value to False?

CodeNewbee
  • 176
  • 1
  • 2
  • 9

2 Answers2

9

patch('some_package.some_other_method') will replace the function some_other_method with a Mock. Now you need to replace the return value of the method some_obj_some_method of this mock:

mock.return_value.some_obj_some_method.return_value = False

The complete example:

# some_package.py

class SomeObject:
    def some_obj_some_method(self):
        raise RuntimeError()


def some_other_method():
    return SomeObject()


def some_method():
    some_obj = some_other_method()
    # This is what you want to mock return value of:
    return some_obj.some_obj_some_method()

Test:

from unittest.mock import patch
from some_package import SomeObject, some_method

@patch('some_package.some_other_method')
def test_some_stuff(function_mock):
    function_mock.return_value.some_obj_some_method.return_value = False
    assert not some_method()

The test will pass as is, will raise a RuntimeError without patching and fail the assertion without the line function_mock.return_value.some_obj_some_method.return_value = False because some_method will only return a Mock that is never False.

hoefling
  • 59,418
  • 12
  • 147
  • 194
2

You can use patch.object

import mock
import some_obj
@mock.patch.object(some_obj, "some_obj_some_method")
def test_some_stuff(mock_some_obj_some_method):
    mock_some_obj_some_method.return_value = False
ashutosh singh
  • 511
  • 3
  • 15
  • I don't think your code will execute - `some_obj` is not a module to import, it's a local variable in `some_method`. – hoefling Jun 26 '19 at 15:26
  • Wouldn't it work if you import `SomeObject` from the file where `some_other_method` is returning it??. I'll test it out. – ashutosh singh Jun 26 '19 at 21:35