我有一个使用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类而不需要构造函数传感器实例作为参数。
答案 0 :(得分:9)
当您致电test_sensor_class.instance
时,您正在使用test_sensor_class
作为财产所有者,请添加Mock属性instance
,并向其添加模拟属性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)