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

后端 未结 4 800
野趣味
野趣味 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:34

    Let me clarify what you're talking about: you want to test Foo in a testcase, which calls external method uses_some_other_method. Instead of calling the actual method, you want to mock the return value.

    class Foo:
        def method_1():
           results = uses_some_other_method()
        def method_n():
           results = uses_some_other_method()
    

    Suppose the above code is in foo.py and uses_some_other_method is defined in module bar.py. Here is the unittest:

    import unittest
    import mock
    
    from foo import Foo
    
    
    class TestFoo(unittest.TestCase):
    
        def setup(self):
            self.foo = Foo()
    
        @mock.patch('foo.uses_some_other_method')
        def test_method_1(self, mock_method):
            mock_method.return_value = 3
            self.foo.method_1(*args, **kwargs)
    
            mock_method.assert_called_with(*args, **kwargs)
    

    If you want to change the return value every time you passed in different arguments, mock provides side_effect.

提交回复
热议问题