Unit testing 如何用PHPUnit模拟这些方法?

Unit testing 如何用PHPUnit模拟这些方法?,unit-testing,testing,mocking,phpunit,Unit Testing,Testing,Mocking,Phpunit,我有这个例子课 class Class { public function getStuff() { $data = $this->getData('Here'); $data2 = $this->getData('There'); return $data . ' ' . $data2; } public function getData( $string ) { retu

我有这个例子课

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

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

        return $data . ' ' . $data2;
    }

    public function getData( $string )
    {
        return $string;
    }
}
我希望能够测试getStuff方法并模拟getData方法

模仿这种方法的最佳方式是什么


谢谢

我认为
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);
mock必须实现一个
TestRepository
接口。这称为依赖注入。例如:

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

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

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

我认为
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);
mock必须实现一个
TestRepository
接口。这称为依赖注入。例如:

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

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

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

谢谢Gargon,这听起来是一个不错的解决方案。如何使用PHPUnit Mock对象实现这一点?我认为它是
$Mock=$this->getMock('TestRepository')。有关更多示例,请参阅Hanks Gargon,这听起来是一个很好的解决方案。如何使用PHPUnit Mock对象实现这一点?我认为它是
$Mock=$this->getMock('TestRepository')。有关更多示例,请参阅