在任何对象实例上存根方法

时间:2016-06-23 09:54:24

标签: php unit-testing phpunit

如何在应用程序中存根硬编码对象的方法?在rspec中有一个方法allow_any_instance_of

我无法扭转依赖关系,对象的初始化应该仍然是硬编码的。

所以,我有ClassA

namespace App
class ClassA
{
  public function doSomething(){
    // more code
    return($sth);
  }
}

用于ClassB

namespace App
class ClassB
{
 protected $instanceOfA;

 public function __construct(){
    $this->instnaceOfA = new ClassA();    
 }

 public function methodToTest(){
   $result = $this->instanceOfA->doSomething()
   // more code
 }
}   

1 个答案:

答案 0 :(得分:1)

我认为这是你正在寻找的东西?一个可插拔的界面?如果你在第33行将classB更改为ClassA,它将切换到另一个类。

Interface TheInterface
{
    public function doSomething();
}

class ClassA implements TheInterface
{
  public function doSomething(){
    echo __METHOD__;
  }
}

class ClassB implements TheInterface
{
  public function doSomething(){
    echo __METHOD__;
  }
}

class ClassProcess
{
 protected $instance;

 public function __construct(TheInterface $class){
    $this->instance = $class;    
 }

 public function methodToTest(){
   $this->instance->doSomething();
 }
}   

$process = new ClassProcess(new ClassB());
$process->methodToTest();