python - 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)
解决方案
unittest.mock.patch
sum
如果需要简单地避免在参数中,也可以用作上下文管理器
class TestCalculator(TestCase):
def test_sum(self):
with patch('calculator.Calculator.sum', return_value=9) as sum:
self.assertEqual(sum(2, 3), 9)
推荐阅读
- javascript - 如果某事物是数字,如何从提示中获取用户输入以签入 while 循环?
- c++ - “大于 0.0”的控件可以在不同的系统上显示不同的行为吗?
- flutter - 颤振/飞镖反射包:不反映基/超类成员
- sql - 如何在 SQL 中计算组的总和?
- json - 从 API 响应到 PostgreSQL 表
- django - SESSION_EXPIRE_AT_BROWSER_CLOSE 我们需要在 django 的项目中写到哪里?
- python - 如何在 Pytorch 中修复或冻结卷积滤波器的子集?
- angular - 为什么我会得到两份 Injectable?
- android - 应用程序从 Google Play 接收更新时的生命周期
- angular - 另一个 ID 为 ####### 的进程当前正在运行 ngcc