[英]unittest.mock.patch a class instance, and set method return values
我有一個使用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實例的構造函數作為論點。
當您調用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.