小编Ate*_*v10的帖子

如何在for循环中动态模拟python函数的结果?

我正在尝试实现一些单元测试来验证包含for循环的方法。此方法接收一个项目列表,并为每个项目执行一个foo()以该项目作为参数的函数。

有谁知道如何模拟该foo()函数以根据作为输入提供的元素动态提供模拟的返回值?

方法:

def foo(i):
    if i == 'this':
        return 'a'
    else:
        return 'b'

def bar(items):
    results = []
    for item in items:
        results.append(foo(item))
    return results
Run Code Online (Sandbox Code Playgroud)

单元测试:

from unittest import TestCase
from mock import patch

class TestCaseBar(TestCase):

    @patch('my_module.foo')
    def test_bar(self, mock_foo):
        mock_foo.return_value = 'dummy'  # I would like to dinamically mock this.
        items = ['this', 'that']
        result = bar(items)
        self.assertEqual(result, ['a', 'b'])
        self.assertTrue(mock_foo.call_count, 2)
    
Run Code Online (Sandbox Code Playgroud)

预先感谢您的回答。

mocking python-3.x python-unittest

2
推荐指数
1
解决办法
5107
查看次数

标签 统计

mocking ×1

python-3.x ×1

python-unittest ×1