0

我有这个示例类

class Class
{
    public function getStuff()
    {
        $data = $this->getData('Here');

        $data2 = $this->getData('There');

        return $data . ' ' . $data2;
    }

    public function getData( $string )
    {
        return $string;
    }
}

我希望能够测试 getStuff 方法并模拟 getData 方法。

模拟这种方法的最佳方法是什么?

谢谢

4

1 回答 1

3

我认为该getData方法应该是不同类的一部分,将数据与逻辑分开。然后,您可以将该类的模拟TestClass作为依赖项传递给实例:

class TestClass
{
  protected $repository;

  public function __construct(TestRepository $repository) {
    $this->repository = $repository;
  }

  public function getStuff()
  {
    $data  = $this->repository->getData('Here');
    $data2 = $this->repository->getData('There');

    return $data . ' ' . $data2;
  }
}

$repository = new TestRepositoryMock();
$testclass  = new TestClass($repository);

模拟必须实现一个TestRepository接口。这称为依赖注入。例如:

interface TestRepository {
  public function getData($whatever);
}

class TestRepositoryMock implements TestRepository {
  public function getData($whatever) {
    return "foo";
  }
}

使用接口并在TestClass构造函数方法中强制执行它的优点是接口保证了您定义的某些方法的存在,就像getData()上面一样 - 无论实现是什么,方法都必须存在。

于 2013-02-17T15:23:57.433 回答