我有一个使用传感器对象的报警对象。在我的测试中,我想用一个存根来修补传感器。下面的代码可以工作,但我必须显式地将存根传递给报警构造函数:
#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)
我想做的,但似乎找不到实现的方法,就是用存根替换传感器实例,而不将anthing传递给警报构造函数。在我看来,这段代码应该可以工作,但不能:
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来测试报警类,而不需要一个以传感器实例为参数的构造函数。
当您调用
test_sensor_class.instance
时,您使用test_sensor_class
作为属性持有者,添加一个模拟属性instance
,并在其中添加一个模拟属性sample_pressure
。你的补丁根本不用,你的代码实际上相当于:您要做的是修补对
Sensor()
的调用。使用代码,只需将模拟类
test_sensor_class
的返回值设置为预设的Sensor
。相关问题 更多 >
编程相关推荐