简体   繁体   English

如何用PHPUnit模拟这些方法?

[英]How To Mock These Methods With PHPUnit?

I have this example class 我有这个例子课

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

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

        return $data . ' ' . $data2;
    }

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

I want to be able to test the getStuff method and mock the getData method. 我希望能够测试getStuff方法并模拟getData方法。

What would be the best way of mocking this method? 模拟该方法的最佳方法是什么?

Thanks 谢谢

I think the getData method should be part of a different class, separating data from logic. 我认为getData方法应该属于不同类的一部分,它将数据与逻辑分开。 You could then pass a mock of that class to the TestClass instance as a dependency: 然后,您可以将该类的模拟作为依赖项传递给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);

The mock would have to implement a TestRepository interface. 该模拟程序必须实现TestRepository接口。 This is called dependency injection. 这称为依赖注入。 Eg: 例如:

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

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

The advantage of using an interface and enforcing it in the TestClass constructor method is that an interface guarantees presence of certain methods that you define, like getData() above - whatever the implementation is, the method must be there. 使用接口并在TestClass构造函数方法中强制执行该接口的优点是,接口可确保存在您定义的某些方法,例如上面的getData() -无论实现如何,该方法都必须存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM