When you call test_sensor_class.instance
you are using test_sensor_class
as a property holder, adding a Mock property instance
to which you add a Mock property sample_pressure
. Your patch is not used at all, your code is in fact equivalent to:
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)
What you want to do it patch the call to Sensor()
.
Using your code, you simply need to set return value of the mocked class test_sensor_class
to a preset mock of 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)