簡體   English   中英

Python 模擬 - 檢查是否在模擬 object 中調用方法

[英]Python mock - Check if methods are called in mocked object

我有一段看起來像這樣的代碼:

# file1.py
from module import Object

def method():
    o = Object("param1")
    o.do_something("param2")

我有如下所示的單元測試:

@patch("file1.Object")
class TestFile(unittest.TestCase):
    def test_call(self, obj):
        ...

我可以在 unittest 中執行obj.assert_called_with()來驗證構造函數是否使用某些參數調用。 是否可以驗證是否使用某些參數調用了obj.do_something 我的直覺是否定的,因為 Mock 完全封裝在 Object 中,但我希望可能有其他方式。

您可以這樣做,因為 arguments 被傳遞給模擬 object。
這應該有效:

@patch("file1.Object")
class TestFile:
    def test_call(self, obj):
        method()
        obj.assert_called_once_with("param1")
        obj.return_value.do_something.assert_called_once_with("param2")

obj.return_value is the Object instance (which is a MagickMock object with the Object spec), and do_something is another mock in that object that is called with the given parameter.

只要您只是將 arguments 傳遞給模擬對象,模擬就會記錄這一點,您可以檢查它。 你沒有的是真正的 function 調用的任何副作用 - 所以如果原來的do_something會調用另一個 function,則無法檢查。

當你模擬 object 時,它也會模擬 object 中的方法。 因此,您可以查看是否使用某些參數調用了obj.do_something ,例如obj.do_something.assert_called_with()

For more information regarding unittest mocking can be found at the python library wiki https://docs.python.org/3/library/unittest.mock.html

該wiki源中存在您所要求的一個完美示例:

>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<Mock name='mock.method()' id='...'>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_with

問候,我看到你把補丁放在 object 上,試着把它放在 function 上,比如:

class TestFile(unittest.TestCase):
    @patch("file1.Object")
    def test_call(self, obj):
        ...

暫無
暫無

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

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