簡體   English   中英

(Python) Mocking 在另一個方法內部調用的方法的返回值

[英](Python) Mocking the return value of a method called inside another method

我有一個 class 和一個 function:

class myclass(object):
    def get_info(self, big_string):
        string_that_always_exists = (big_string.split("Name: myname ")[1]).split("\n")[0]
        if "Name: " in big_string:
            result = self.find_details(string_that_always_exists)
            return result
        else:
            return None

    def find_details(string_that_always_exists):
        # sorts through huge string
        return dictionary_big

我需要做的是編寫一個單元測試來修補方法 find_details(string_that_always_exists) 所以它總是等於同一個字典。

我什至不想發布我嘗試過的內容,因為我真的不明白 unittest.test 框架是如何工作的,但我認為它會給出一些想法:

@patch('myclass.find_details')
def test_get_info(self, mock_method):
    mock_method.return_value = Mock(myclass)
    mock_method.find_details.return_value = ["item 1", "item 2", "item 3", "item 4"]
    results = mock_method.get_info("big string with only one guaranteed sub string. Name: ")
    self.assertEqual(results[0], "item 1")

以上不起作用。 結果始終等於 MagicMock object,當我調試程序時,結果中沒有返回值。 我認為這是因為我沒有正確指定我的補丁,但老實說我不知道。

你的測試有一些問題。 首先,我不確定您是否是 mocking 正確的 object,可能您只是沒有顯示真正的模擬字符串。 模擬字符串應引用 object 以便可以導入,包括模塊名稱。

其次,你不是在測試你的 class,而是一個模擬。 您應該實例化您的真實 class 並對其進行測試。

第三,您將 return_value 設置在錯誤的位置。 您已經模擬了 function,因此您只需模擬 function 的返回值。

最后,您的測試只會返回None ,因為您的參數不包含“文本”,但這可能不是您真正的測試。 作為旁注:它有助於提供真正的工作代碼,即使它沒有做你想要的。

您的測試可能看起來像這樣(假設您 class 位於mymodule.py中):

import unittest
from unittest.mock import patch

from mymodule import myclass

class TestMyClass(unittest.TestCase):
    @patch('mymodule.myclass.find_details')
    def test_get_info(self, mock_method):
        mock_method.return_value = ["item 1", "item 2", "item 3", "item 4"]
        cls = myclass()
        results = cls.get_info("Big string with text. Name: ")
        self.assertEqual(results[0], "item 1")

暫無
暫無

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

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