簡體   English   中英

從函數內部創建的對象中模擬方法調用(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()類在另一個包中定義。 我試圖用模擬對它進行單元測試,如下所示:

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

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

如果您的課程在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()

PS堆疊裝飾器是從底部添加的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM