【发布时间】:2013-10-27 15:27:42
【问题描述】:
我正在为我的一个控制器编写 CakePHP 单元测试。控制器对AuthComponent::user() 方法进行了多次调用,以读取当前登录用户的数据。有3种用法:
-
AuthComponent::user()(无参数,获取整个数组) -
AuthComponent::user('id')(获取用户 ID) -
AuthComponent::user('name')(获取用户名)
我在测试中尝试了两种模拟 AuthComponent 的方法:
// Mock the Controller and the Components
$this->controller = $this->generate('Accounts', array(
'components' => array(
'Session', 'Auth' => array('user'), 'Acl'
)
));
// Method 1, write the entire user array
$this->controller->Auth->staticExpects($this->any())->method('user')
->will($this->returnValue(array(
'id' => 2,
'username' => 'admin',
'group_id' => 1
)));
// Method 2, specifically mock the AuthComponent::user('id') method
$this->controller->Auth->staticExpects($this->any())->method('user')
->with('id')
->will($this->returnValue(2));
不过,这些方法对我不起作用。方法 1 似乎根本没有做任何事情,我的控制器中使用当前登录用户 id 的保存操作返回 null,因此该值未正确设置/获取。
方法 2 似乎可行,但过于宽泛,它还尝试将自己绑定到 AuthComponent::user() 调用(没有参数的调用),但失败并出现错误:
方法名称的期望失败等于何时 调用零次或多次参数 0 用于调用 AuthComponent::user(null) 与预期值不匹配。失败的 断言 null 匹配预期的“id”。
如何为 AuthComponent 获取适当的模拟,以便获取所有字段/变量?
【问题讨论】:
标签: php unit-testing cakephp phpunit