【问题标题】:Python Unit Test Patch Function - Avoid passing mocked function to test functionPython 单元测试补丁函数 - 避免将模拟函数传递给测试函数
【发布时间】:2020-02-27 21:28:22
【问题描述】:

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

# 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)

【问题讨论】:

  • 你到底想做什么?从查看patch 的文档来看,似乎期望 classes 作为输入,而不是函数。我错过了什么吗?
  • 我相信函数可以被模拟。这是我关注的示例 - semaphoreci.com/community/tutorials/…
  • 你为什么要嘲讽什么?您在这里所做的只是测试您的模拟是否确实返回9。也就是说,你写了一个更详细的self.assertEqual(9, 9)。
  • 我没有时间在代码中进行测试,但是从补丁的文档看来,如果您不指定 new 参数,那么您必须按照上述方式进行。如果您指定 new 参数(可能指向另一个类或函数),那么您可以跳过修饰函数签名中的第二个参数。我不知道你是否可以通过 lambda 指定这样一个新函数。

标签: python python-3.x pytest


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 2017-11-15
    • 2014-10-21
    • 2016-11-29
    • 2019-04-09
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多