【问题标题】:unittest.mock.patch a class instance, and set method return valuesunittest.mock.patch 一个类实例,并设置方法返回值
【发布时间】:2013-09-23 05:33:33
【问题描述】:

我有一个使用 Sensor 对象的 Alarm 对象。在我的测试中,我想用 Stub 修补 Sensor。下面的代码有效,但我必须将存根显式传递给 Alarm 构造函数:

#tire_pressure_monitoring.py
from sensor import Sensor

class Alarm:

    def __init__(self, sensor=None):
        self._low_pressure_threshold = 17
        self._high_pressure_threshold = 21
        self._sensor = sensor or Sensor()
        self._is_alarm_on = False

    def check(self):
        psi_pressure_value = self._sensor.sample_pressure()
        if psi_pressure_value < self._low_pressure_threshold or self._high_pressure_threshold < psi_pressure_value:
            self._is_alarm_on = True

    @property
    def is_alarm_on(self):
        return self._is_alarm_on

#test_tire_pressure_monitoring.py
import unittest
from unittest.mock import patch, MagicMock, Mock

from tire_pressure_monitoring import Alarm
from sensor import Sensor

class AlarmTest(unittest.TestCase):

    def test_check_with_too_high_pressure(self):
        with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
            test_sensor_class.instance.sample_pressure.return_value=22
            alarm = Alarm(sensor=test_sensor_class.instance)
            alarm.check()
            self.assertTrue(alarm.is_alarm_on)

我想做但似乎找不到实现的方法是用存根替换 Sensor 实例,而不将 anthing 传递给 Alarm 构造函数。这段代码在我看来应该可以工作,但没有:

    def test_check_with_too_high_pressure(self):
    with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
        test_sensor_class.instance.sample_pressure.return_value=22
        alarm = Alarm()
        alarm.check()
        self.assertTrue(alarm.is_alarm_on)

Alarm 实例获取了一个 MagicMock 实例,但“sample_pressure”方法不返回 22。基本上我想知道是否有一种方法可以使用 unittest.mock 来测试 Alarm 类,而无需构造函数一个 Sensor 实例作为参数。

【问题讨论】:

    标签: python unit-testing mocking stub


    【解决方案1】:

    当您调用 test_sensor_class.instance 时,您正在使用 test_sensor_class 作为属性持有者,添加一个 Mock 属性 instance,您向其中添加一个 Mock 属性 sample_pressure。你的补丁根本没用,你的代码其实相当于:

    def test_check_with_too_high_pressure(self):
        instance = MagicMock()
        instance.sample_pressure.return_value=22
        alarm = Alarm(sensor=instance)
        alarm.check()
        self.assertTrue(alarm.is_alarm_on)
    

    您想做什么,将呼叫修补到Sensor()

    使用您的代码,您只需将模拟类test_sensor_class 的返回值设置为Sensor 的预设模拟。

    def test_check_with_too_high_pressure(self):
        with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
            mockSensor = MagicMock()
            mockSensor.sample_pressure.return_value = 22
            test_sensor_class.return_value = mockSensor
            alarm = Alarm()
            alarm.check()
            self.assertTrue(alarm.is_alarm_on)
    

    【讨论】:

      猜你喜欢
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2019-01-12
      • 2020-10-08
      • 1970-01-01
      • 2015-12-14
      相关资源
      最近更新 更多