4

Sensor オブジェクトを使用する Alarm オブジェクトがあります。私のテストでは、センサーにスタブをパッチしたいと思います。以下のコードは機能しますが、スタブを 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 インスタンスをスタブに置き換えることです。このコードは機能するはずですが、機能しません。

    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 を使用して、Sensor インスタンスを取るコンストラクターを必要とせずに Alarm クラスをテストする方法があるかどうかを知りたいです。引数として。

4

1 に答える 1

12

プロパティホルダーとしてtest_sensor_class.instance使用している場合は、モックプロパティを追加するモックプロパティを追加します。パッチはまったく使用されていません。コードは実際には次と同等です。test_sensor_classinstancesample_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)
于 2013-09-18T13:39:11.303 に答える