代码之家  ›  专栏  ›  技术社区  ›  Vishwaksena

我们可以用mockito模拟间谍对象吗?

  •  1
  • Vishwaksena  · 技术社区  · 8 年前

    我有一个叫做RadiationControl的类,我用下面的方法为它创建了一个间谍。

    RadiationControl radCtrl = new RadiationControl();
    RadiationControl spyRadCtrl = Mockito.spy(radCtrl);
    

    我在另一个名为StationMonitor的类中有一个链式方法调用,该类是通过使用RadiationControl对象调用的。当我尝试使用上面创建的spy并尝试访问具有方法参数的内容时,它们会随着时间的推移而变化。

    StationMonitorObject stationMonitorObject = radCtrl.getStationMonitorLoader().retrieveCVStationMonitorObject(Long.parseLong(syngId), status);
    

    因此,使用上述语法,当我尝试为该方法调用stub间谍时,它会抱怨stub正确。

    StationMonitorLoader stationMonitorLoader = StationMonitorLoader.getLoader(domain);
      Mockito.doReturn(stationMonitorLoader).when(spyRadCtrl).getStationMonitorLoader();
    
      Mockito.doReturn(stationMonitorObject).when(stationMonitorLoader).retrieveCVStationMonitorObject(any(Long.class), null);
    

    有没有更好的方法来应对这种情况?

    1 回复  |  直到 8 年前
        1
  •  4
  •   Timothy Truckle Vincent Boutot    8 年前

    有没有更好的方法来应对这种情况?

    对

    这里的问题是:

    radCtrl.getStationMonitorLoader()
           .retrieveCVStationMonitorObject(Long.parseLong(syngId), status);
    

    这违反了 德米特定律 (又名 不要和陌生人说话! ).

    方法 retrieveCVStationMonitorObject() 应在课堂上提供 RadiationControl 并将呼叫委托给 它的 依赖关系(看起来像是 StationMonitorLoader ...)