在模拟对象上多次调用staticExpects

时间:2012-05-13 23:16:16

标签: unit-testing cakephp phpunit

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

这是我的代码的一部分。

$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与期望值不匹配。 无法断言两个字符串相等。

请帮助:)

1 个答案:

答案 0 :(得分: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”