如何在PHPSpec中创建一个模拟数组?

问题描述:

我刚开始使用PHPSpec,我真的很喜欢PHPUnit,尤其是努力的模拟和存根(stub)。无论如何,我试图测试的方法需要一个Cell对象的数组。我如何告诉PHPSpec给我一些模拟?如何在PHPSpec中创建一个模拟数组?

简体版我班的

<?php 
namespace Mything; 

class Row 
{ 
    /** @var Cell[] */ 
    protected $cells; 


    /** 
    * @param Cell[] $cells 
    */ 
    public function __construct(array $cells) 
    { 
     $this->setCells($cells); 
    } 

    /** 
    * @param Cell[] $cells 
    * @return Row 
    */ 
    public function setCells(array $cells) 
    { 
     // validate that $cells only contains instances of Cell 

     $this->cells = $cells; 

     return $this; 
    } 
} 

我的测试

<?php 
namespace spec\MyThing\Row; 

use MyThing\Cell; 
use PhpSpec\ObjectBehavior; 

class RowSpec extends ObjectBehavior 
{ 
    function let() 
    { 
     // need to get an array of Cell objects 
     $this->beConstructedWith($cells); 
    } 

    function it_is_initializable() 
    { 
     $this->shouldHaveType('MyThing\Row'); 
    } 

    // ... 
} 

我希望我可以做到以下几点,但后来它抱怨找不到Cell[]的简化版本。它使用FQN抱怨无法找到\MyThing\Cell[]

/** 
* @param Cell[] $cells 
*/ 
function let($cells) 
{ 
    // need to get an array of Cell objects 
    $this->beConstructedWith($cells); 
} 

我能算出唯一选项是通过多个类型暗示Cell参数,并手动将它们组合成一个数组。我错过了一些简单的东西吗

编辑:我使用PHPSpec 2.5.3的,不幸的是,服务器目前停留在PHP 5.3 :-(

你为什么不这样做

use Prophecy\Prophet; 
use Cell; // adapt it with PSR-4 and make it use correct class 

class RowSpec extends ObjectBehavior 
{ 
    private $prophet; 
    private $cells = []; 

    function let() 
    { 
     $this->prophet = new Prophet(); 

     for ($i = 0; $i < 10; $i++) { 
      $this->cells[] = $this->prophet->prophesize(Cell::class); 
     } 
     $this->beConstructedWith($cells); 
    } 
    // .... 

    function letGo() 
    { 
     $this->prophet->checkPredictions(); 
    } 

    public function it_is_a_dummy_spec_method() 
    { 
     // use here your cells mocks with $this->cells 
     // and make predictions on them 
    } 
} 

说明

let函数中你实例化了一个Prophet对象,它基本上是一个与PHPSpec(它本身使用预言)串联使用的模拟库/框架。
我建议保留实例($this->prophet),这对于后续步骤很有用。

现在,您必须创建您的模拟,并且您可以使用prophetprophesize
即使对于嘲笑,我建议将它们保留为一个私有变量,您可以使用可能在您的方法中进行预测。

letGo功能是在这里明确地检查cells所做的预期:没有,cellsstubsdummies

当然,通过方法签名模拟并且明确跳过checkPredictions是方便的,但只要您需要一个模拟数组,我想这是实现您的目标的唯一方法。