【问题标题】:phpspec - specify that arguments should be passed to mock objectphpspec - 指定参数应该传递给模拟对象
【发布时间】:2015-04-10 18:43:02
【问题描述】:

一般来说,我是 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();
    }
}

当我运行规范时,检查器类中的实现之前我得到:

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()

什么给了?据我所知,我按照规定实现了。

【问题讨论】:

    标签: php phpspec


    【解决方案1】:

    我明白了:

    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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-07
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      相关资源
      最近更新 更多