Using python's mock patch.object to change the return value of a method called within another method

后端 未结 4 801
野趣味
野趣味 2020-12-12 18:10

Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods

4条回答
  •  生来不讨喜
    2020-12-12 18:38

    This can be done with something like this:

    # foo.py
    class Foo:
        def method_1():
            results = uses_some_other_method()
    
    
    # testing.py
    from mock import patch
    
    @patch('Foo.uses_some_other_method', return_value="specific_value"):
    def test_some_other_method(mock_some_other_method):
        foo = Foo()
        the_value = foo.method_1()
        assert the_value == "specific_value"
    

    Here's a source that you can read: Patching in the wrong place

提交回复
热议问题