簡體   English   中英

如何多次模擬函數的返回值

[英]How to mock return value to a function multiple times

我有 func1() ,它根據不同的輸入多次調用 func2() 。 我現在想通過模擬 func2() 的返回值來為 func1() 編寫單元測試。 func2() 根據提供的輸入返回字符串。 詳情如下:

input_list = ["1", "2", "3"]
def func1(input_list):
    if "1" in input_list:
        response = func2("1")
        // Do something based on response
    if "2" in input_list:
        response = func2("2")
        // Do something based on response
    if "3" in input_list:
        response = func2("3")
        // Do something based on response
    return True //Based on some logic provided by response variable.

單元測試如下所示:

def test_case1():
    expected_response = True
    sample_input = ["1","2"]
    assert func1(sample_input) // Here I want to mock func2(), but not sure how ?

我嘗試在多個論壇中搜索,發現可以使用side_effect ,但不知道如何在我的情況下使用它。

您可以為side_effect分配一個函數。

用於引發異常或動態更改返回值。

例如

example.py



def func1(input_list):
    if "1" in input_list:
        return func2("1")
    if "2" in input_list:
        return func2("2")
    if "3" in input_list:
        return func2("3")
    return True


def func2(input):
    pass

test_example.py

import unittest
from unittest.mock import patch
from example import func1


class TestExample(unittest.TestCase):
    @patch('example.func2')
    def test_func1(self, mock_func2):
        def side_effect(input):
            if input == '1':
                return 'a'
            if input == '2':
                return 'b'
            if input == '3':
                return 'c'

        mock_func2.side_effect = side_effect
        actual1 = func1(['1'])
        self.assertEqual(actual1, 'a')
        actual2 = func1(['2'])
        self.assertEqual(actual2, 'b')
        actual3 = func1(['3'])
        self.assertEqual(actual3, 'c')


if __name__ == '__main__':
    unittest.main()

單元測試結果:

⚡  coverage run /Users/dulin/workspace/github.com/mrdulin/python-codelab/src/stackoverflow/64679177/test_example.py && coverage report -m --include='./src/**'
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Name                                         Stmts   Miss  Cover   Missing
--------------------------------------------------------------------------
src/stackoverflow/64679177/example.py           10      2    80%   10, 14
src/stackoverflow/64679177/test_example.py      22      0   100%
--------------------------------------------------------------------------
TOTAL                                           32      2    94%

暫無
暫無

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

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