首页 > 解决方案 > Python 单元测试补丁函数 - 避免将模拟函数传递给测试函数

问题描述

我正在尝试模拟类似于下面的 python 函数。我没有对模拟函数做任何事情,除了它用于在被调用函数中返回模拟数据。我是否可以避免将变量(在这种情况下为总和)传递给测试函数?

# test_calculator.py

from unittest import TestCase
from unittest.mock import patch

class TestCalculator(TestCase):
    @patch('calculator.Calculator.sum', return_value=9)
    def test_sum(self, sum):
        self.assertEqual(sum(2,3), 9)

标签: pythonpython-3.xpytest

解决方案


unittest.mock.patchsum如果需要简单地避免在参数中,也可以用作上下文管理器

class TestCalculator(TestCase):
    def test_sum(self):
        with patch('calculator.Calculator.sum', return_value=9) as sum:
            self.assertEqual(sum(2, 3), 9)

推荐阅读