【问题标题】:Multiple calls to staticExpects on mocked objects在模拟对象上多次调用 staticExpects
【发布时间】:2012-05-21 12:03:34
【问题描述】:

我正在尝试在 cakephp 中为我的控制器编写测试用例,到目前为止,我已经设法模拟了控制器并包含了在我的控制器功能中使用的 auth 组件。问题是我似乎只能调用一次staticExpects,这意味着我只能为一个函数调用定义一个返回值,我不希望这样,我需要在同一个测试用例中多次调用staticExpects。

这是我的代码的一部分。

$this->TasksController = $this->generate('Tasks', array(
'components' => array('Session','Auth' => array('User'), ) ));

  $this->TasksController->Auth->staticExpects($this->any())
    ->method('User')
    ->with('userID')
    ->will($this->returnValue(224));
     $this->TasksController->Auth->staticExpects($this->any())
    ->method('User')
    ->with('accID')
    ->will($this->returnValue('some ID here'));

每当我这样做并运行测试时,它都会给我这个错误

方法名称的期望失败等于调用零次或多次时 调用 AuthComponent::user('userID') 的参数 0 与预期值不匹配。 断言两个字符串相等失败。

请帮忙:)

【问题讨论】:

    标签: unit-testing cakephp phpunit


    【解决方案1】:

    您必须指定何时使用 $this->at(index) 调用静态方法。

    $this->TasksController->Auth->staticExpects($this->at(1))
        ->method('user')
        ->with('userID')
        ->will($this->returnValue(224));
    
    $this->TasksController->Auth->staticExpects($this->at(2))
        ->method('user')
        ->with('accID')
        ->will($this->returnValue('some ID here'));
    

    如果您不确定何时调用它们,请逐个尝试每个期望,直到错误消息为您提供所调用的内容

    --- Expected
    +++ Actual
    @@ @@
    -'userID'
    +'accID'
    

    最后一件事,正确的方法名称是“user”而不是“User”

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多