duanji8615 2013-05-12 17:13
浏览 29

在什么情况下方法是可测试的

I think I understand why methods using other static methods are difficult to test. When I say test I'm thinking of Unit Testing.

Take this example:

class foo {
  protected $objA;
  public function m1() {
    $objA = new A();
    $objA->show();
  }

  public function m2() {
    A::show();
  }

  public function m3() {
    $this->objA->show();
  }

  public function m4($objA) {
    $objA->show();
  }

}
  • Is m1 easy to test? I think not because you can't mock that object.
  • Is m2 the case where static makes testing difficult?
  • Is m3 a good testable method?
  • Is m4 a good testable method?

Did I got this right?

  • 写回答

1条回答 默认 最新

  • douliao8318 2013-05-12 17:34
    关注

    M1 isn't perfect because you have a concrete reference to a class in the method itself, and so you're correct in that you won't be able to mock it. In this situation you should use dependency injection to pass an object reference to the method.

    M2 is pretty much the same situation, in that it's using a concrete reference, but as you pointed out, it's using a static method instead. Static methods are difficult to mock because there's no way to create an interface that defines static methods (I'm speaking from a .Net background, I'm not sure whether you can interface static methods in PHP, but I doubt it).

    M3, looks like you're using property injection, in which case yes, this is an easily mockable test, because the object is instantiated outside of the class itself and passed to it.

    M4 is the same as M3 because the dependency injection comes in the form of a method parameter.

    Ideally dependency injection should be done at class level, either by using properties or constructor parameters. Constructor parameters are generally viewed as the preferred method, because property injection, at least from my perspective, is a little loose, whereas constructor injection forces you to create a class with every dependency it requires.

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line