加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

单元测试 – 如何使用依赖注入而不破坏封装?

发布时间:2020-12-14 01:05:57 所属栏目:百科 来源:网络整理
导读:如何在不破坏封装的情况下执行依赖注入? 使用Dependency Injection example from Wikipedia: public Car { public float getSpeed();} Note: Other methods and properties (e.g. PushBrake(),PushGas(), SetWheelPosition() ) omitted for clarity 这工作
如何在不破坏封装的情况下执行依赖注入?

使用Dependency Injection example from Wikipedia:

public Car {
    public float getSpeed();
}

Note: Other methods and properties (e.g. PushBrake(),PushGas(),
SetWheelPosition() ) omitted for
clarity

这工作得很好;你不知道我的对象如何实现getSpeed – 它是“封装”。

实际上,我的对象实现getSpeed as:

public Car {
    private m_speed;
    public float getSpeed( return m_speed; );
}

一切都很好。有人构造我的Car对象,捣碎踏板,喇叭,方向盘和汽车响应。

现在让我说我改变我的车的内部实现细节:

public Car {
    private Engine m_engine;
    private float m_currentGearRatio;
    public float getSpeed( return m_engine.getRpm*m_currentGearRatio; );
}

一切都很好。汽车遵循适当的OO原则,隐藏了事情做的细节。这释放了调用者解决他的问题,而不是试图了解一辆汽车如何工作。它也给了我自由改变我的实现,因为我认为合适。

但依赖注入会迫使我暴露我的类到一个Engine对象,我没有创建或初始化。更糟的是,我现在暴露了我的车甚至有一个引擎:

public Car {
   public constructor(Engine engine);
   public float getSpeed();
}

现在外面的词意识到我使用引擎。我没有总是使用引擎,我可能想不使用引擎在未来,但我不能再改变我的内部实现:

public Car {
    private Gps m_gps;
    public float getSpeed( return m_gps.CurrentVelocity.Speed; )
}

不中断调用者:

public Car {
   public constructor(Gps gps);
   public float getSpeed();
}

但依赖注入打开了整个蠕虫:通过打开整个蠕虫。依赖注入需要我所有的对象私有实现细节暴露。我的Car类的消费者现在必须理解和处理我以前隐藏的内部复杂的我的类:

public Car {
   public constructor(
       Gps gps,Engine engine,Transmission transmission,Tire frontLeftTire,Tire frontRightTire,Tire rearLeftTire,Tire rearRightTire,Seat driversSeat,Seat passengersSeat,Seat rearBenchSeat,SeatbeltPretensioner seatBeltPretensioner,Alternator alternator,Distributor distributor,Chime chime,ECM computer,TireMonitoringSystem tireMonitor
       );
   public float getSpeed();
}

我如何使用依赖注入的优点来帮助单元测试,同时不打破封装的优点来帮助可用性?

也可以看看

> Must Dependency Injection come at the expense of Encapsulation?(必须,而不是如何)

为了乐趣,我可以减少getSpeed示例,只需要什么:

public Car {
   public constructor(
       Engine engine,Tire frontRightTire
       TireMonitoringSystem tireMonitor,UnitConverter unitsConverter
       );
   public float getSpeed()
   {
      float tireRpm = m_engine.CurrentRpm * 
              m_transmission.GetGearRatio( m_transmission.CurrentGear);

      float effectiveTireRadius = 
         (
            (m_frontLeftTire.RimSize + m_frontLeftTire.TireHeight / 25.4)
            +
            (m_frontRightTire.RimSize + m_frontRightTire.TireHeight / 25.4)
         ) / 2.0;

      //account for over/under inflated tires
      effectiveTireRadius = effectiveTireRadius * 
            ((m_tireMonitor.FrontLeftInflation + m_tireMontitor.FrontRightInflation) / 2.0);

      //speed in inches/minute
      float speed = tireRpm * effetiveTireRadius * 2 * Math.pi;

      //convert to mph
      return m_UnitConverter.InchesPerMinuteToMilesPerHour(speed);
   }
}

更新:也许一些答案可以跟随问题的先行,并提供示例代码?

public Car {
    public float getSpeed();
}

另一个例子是当我的类依赖另一个对象时:

public Car {
    private float m_speed;
}

在这种情况下,float是一个用于表示浮点值的类。从我读到,每个依赖类应该注入 – 以防我想嘲笑浮动类。这引起了注入每个私有成员的幽灵,因为一切都从根本上是一个对象:

public Car {
    public Constructor(
        float speed,float weight,float wheelBase,float width,float length,float height,float headRoom,float legRoom,DateTime manufactureDate,DateTime designDate,DateTime carStarted,DateTime runningTime,Gps gps,TireMonitoringSystem tireMonitor,...
     }

这些真正的实现细节,我不想让客户看看。

许多其他答案提示,但我要更明确地说,是的,幼稚的依赖注入的实现可以打破封装。

避免这一点的关键是调用代码不应该直接实例化依赖(如果它不关心它们)。这可以以多种方式完成。

最简单的就是有一个默认的构造函数,注入默认值。只要调用代码只使用默认构造函数,您可以更改幕后的依赖关系,而不会影响调用代码。

如果你的依赖项本身有依赖性等等,这可能开始失去控制。此时,Factory模式可以到位(或者您可以从get-go中使用它,以便调用代码已经使用工厂)。如果你介绍了工厂,并且不想破坏你的代码的现有用户,你总是可以从默认的构造函数调用到工厂。

除此之外,还有使用反转控制。我没有使用IoC足以说太多,但有很多问题在这里以及在线文章解释它比我可以更好。

如果它应该被真正封装到调用代码不能知道依赖的地方,那么可以选择使注入(具有相关性参数的构造函数或setter)内部如果语言支持它,或使它们是私有的,单元测试使用像Reflection如果你的语言支持它。如果你的语言支持既不然,我认为一个可能性可能是让类调用代码实例化一个虚拟类,只是封装类,真正的工作(我相信这是门面模式,但我从来不记得名称正确):

public Car {
   private RealCar _car;
   public constructor(){ _car = new RealCar(new Engine) };
   public float getSpeed() { return _car.getSpeed(); }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读