【问题标题】:How can I create an array of mocks in PHPSpec?如何在 PHPSpec 中创建一个模拟数组?
【发布时间】:2016-09-28 14:05:14
【问题描述】:

我刚刚开始使用 PHPSpec,我真的很喜欢 PHPUnit,尤其是轻松的模拟和存根。无论如何,我试图测试的方法需要一个 Cell 对象数组。如何告诉 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 :-(

【问题讨论】:

    标签: php unit-testing phpspec


    【解决方案1】:

    你为什么不做类似的事情

    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(本身使用Prophecy)一起使用的模拟库/框架。
    我建议保留该实例 ($this-&gt;prophet),以便对后续步骤有用。

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

    letGo 函数在这里明确检查您对cells 的期望:没有,cells 只有stubsdummies

    当然,通过方法签名传递一个模拟并显式跳过checkPredictions 很方便,但是,一旦您需要一个模拟数组,我想这是实现目标的唯一方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-10
      • 2021-02-22
      相关资源
      最近更新 更多