簡體   English   中英

如何使用 with 語句修補 python 單元測試中的多個輸入 - 無裝飾器

[英]How to patch multiple inputs in python unit test using with statement - no decorators

我在看過這兩個類似的問題后問這個問題:

如何在 python 單元測試中修補多個重復輸入?

Python 模擬多個返回值

但兩者都沒有令人滿意地給我我正在尋找的答案。

我需要能夠使用 with 語句而不是裝飾器來修補對input()的多個調用。

原因是我正在編寫的測試不允許我使用裝飾器,也不允許修改測試方法的簽名以添加模擬輸入,如下所示:

@mock.patch('builtins.input')
def test_myMethod(self, mocked_input):
    mock_args = ['20', 100]
    mocked_input.side_effect = mock_args
    res = mymethod()
    self.assertEqual(res, 120)

我的問題是如何使用 as with 語句達到與以下相同的效果:

def test_myMethod(self):
    with mock.patch('builtins.input', ...)

任何幫助將不勝感激

使用as...以獲取由with語句創建的模擬實例:

def test_myMethod(self):
    mock_args = ['20', 100]
    with mock.patch('builtins.input') as mocked_input:
        mocked_input.side_effect = mock_args
        res = mymethod()
    self.assertEqual(res, 120)

或者,您可以將副作用直接傳遞給patch調用:

def test_myMethod(self):
    mock_args = ['20', 100]
    with mock.patch('builtins.input', side_effect=mock_args):
        res = mymethod()
    self.assertEqual(res, 120)

如您所見,在特定情況下執行此操作意味着您甚至不需要對模擬實例的引用。

暫無
暫無

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

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