繁体   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