从函数内部创建的对象模拟方法调用 (python)

Mock a method call from an object created inside a function (python)

class Foo:
       def do_work:
          client = Client()
          client.widgets(self.widget_id).parts().get()``

我有上面的代码。 Client() class 在另一个包中定义。 我正在尝试使用 mock 对其进行单元测试,如下所示:

    magic_mock = MagicMock()
    api_client = Client()
    magic_mock.api_client.widgets().parts().get.return_value = self.generate_mock

不幸的是,它似乎不起作用。什么是更好的方法?

如果你的 class 在 mymodule.py:

# mymodule.py
from othermodule import Client

class Foo:
    def do_work():
        client = Client()
        return client.widgets(self.widget_id).parts().get()

那么你的测试模块应该是这样的(实现 generate_mock 而不是 mocked_value):

# test_mymodule.py
from unittest.mock import patch

import mymodule


@patch('mymodule.Client')
def test_client_widgets_parts_get_returned(mocked):
    mocked_value = "foo"
    mocked.return_value.widgets.return_value.parts.return_value.get.return_value = mocked_value
    returned = mymodule.Foo().do_work()
    assert returned == mocked_value

或者不改变你的 do_work:

@patch('mymodule.Client')
def test_client_widgets_parts_get_called(mocked):
    mymodule.Foo().do_work()
    mocked.return_value.widgets.return_value.parts.return_value.get.assert_called()

P.S。从底部添加堆叠装饰器:

@patch('mymodule.Other')
@patch('mymodule.Client')
def test_client_widgets_parts_get_called(mocked_client, mocked_other):