phpspec - 指定应将参数传递给mock对象

时间:2015-04-10 18:43:02

标签: php phpspec

我是PHPSpecBDD/TDD的新手。

给出以下代码:

interface Checker
{
    public function execute(array $args = array());
}

class Check
{
    public $checker;

    public $params = array();

    public function doCheck()
    {
    }
}

我想指定Check类需要将它的参数传递给Checker,但我不确定该怎么做。

我的规格:

class CheckSpec extends ObjectBehavior
{    
    function it_should_pass_params_to_checker_on_execute(\Checker $checker)
    {
        $checker->execute()->willReturn(true);
        $this->checker = $checker;
        $this->params = array(1,2);
        $this->doCheck();
        $checker->execute(array(1,2))->shouldHaveBeenCalled();
    }
}

当我运行规范时,之前在Checker Class中的实现我得到:

9  - it should pass params to checker on execute
  no calls been made that match:
    Double\Checker\P1->execute(exact([1, 2]))
  but expected at least one.

一旦实施:

class Check
{
    public $checker;

    public $params = array();

    public function doCheck()
    {
        $this->checker->execute($this->params);
    }
}

我明白了:

9  - it should pass params to checker on execute
  method call:
    - execute([1, 2])
  on Double\Checker\P1 was not expected, expected calls were:
    - execute()

是什么给出的?据我所知,我按规定实施。

1 个答案:

答案 0 :(得分:0)

我明白了:

class CheckSpec extends ObjectBehavior
{    
    function it_should_pass_params_to_checker_on_execute(\Checker $checker)
    {
        // I should've created my mock with the expected parameters
        $checker->execute(array(1,2))->willReturn(true);
        // Like so ------>^^^^^^^^^^^      
        $this->checker = $checker;
        $this->params = array(1,2);
        $this->doCheck();
        $checker->execute(array(1,2))->shouldHaveBeenCalled();
    }
}