【问题标题】:How To Mock These Methods With PHPUnit?如何用 PHPUnit 模拟这些方法?
【发布时间】:2013-02-02 01:44:03
【问题描述】:

我有这个示例类

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

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

        return $data . ' ' . $data2;
    }

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

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

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

谢谢

【问题讨论】:

    标签: unit-testing testing mocking phpunit


    【解决方案1】:

    我认为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() - 无论实现是什么,方法都必须存在。

    【讨论】:

    • 感谢 Gargon,这听起来是个不错的解决方案。使用 PHPUnit 模拟对象如何做到这一点?
    • 我认为是$mock = $this->getMock('TestRepository');。更多示例请参考the PHPUnit documentation
    猜你喜欢
    • 2014-10-09
    • 2019-08-07
    • 2013-01-27
    • 2020-11-15
    • 1970-01-01
    • 2017-02-27
    • 2016-06-13
    • 2021-04-27
    • 1970-01-01
    相关资源
    最近更新 更多