Unit testing CakePHP单元测试模拟身份验证组件
代码Unit testing CakePHP单元测试模拟身份验证组件,unit-testing,cakephp,mocking,cakephp-2.0,Unit Testing,Cakephp,Mocking,Cakephp 2.0,代码 class AclRowLevelsController extends AppController { public $components = array( // Don't use same name as Model '_AclRowLevel' => array('className' => 'AclRowLevel') ); public function view() { $thi
class AclRowLevelsController extends AppController {
public $components = array(
// Don't use same name as Model
'_AclRowLevel' => array('className' => 'AclRowLevel')
);
public function view() {
$this->_AclRowLevel->checkUser();
...
}
}
class AclRowLevelComponent extends Component {
public function initialize(Controller $controller) {
$this->controller = $controller;
$this->AclRowLevel = ClassRegistry::init('AclRowLevel');
}
public function checkUser($permission, $model) {
$row = $this->AclRowLevel->find('first', array(
'conditions' => array(
'model' => $model['model'],
'model_id' => $model['model_id'],
'user_id' => $this->controller->Auth->user('id')
)
));
}
}
class AclRowLevelsControllerTest extends ControllerTestCase {
public function testViewAccessAsManager() {
$AclRowLevels = $this->generate('AclRowLevels', array(
'components' => array(
'Auth' => array(
'user'
),
'Session',
)
));
$AclRowLevels->Auth
->staticExpects($this->any())
->method('user')
->with('id')
->will($this->returnValue(1));
$this->testAction('/acl_row_levels/view/Task/1');
}
问题
AclRowLevel组件中的查询需要身份验证用户id。我想为单元测试模拟用户id值“1”。
测试中的模拟身份验证方法“user”不适用于来自组件的调用。因此,该查询中的用户id的值为null
这应该怎么做?进行调试($AclRowLevels->Auth)
检查它是否真的被嘲笑过。它应该是一个模拟对象。如果不是出于某种原因,请尝试:
$AclRowLevels->Auth = $this->getMock(/*...*/);
顺便说一下,checkUser()中的代码应该进入模型。我也怀疑这一定是一个组成部分。这似乎是用来授权的,为什么不呢?这就是我想要的:
$AclRowLevels->Auth
->staticExpects($this->any())
->method('user')
->will($this->returnCallback(
function($arg) {
if ($arg === 'id') {
return 1;
}
return null;
}
));
身份验证对象已被模拟?请参见$this->generate。这段代码出现在组件中是有原因的。并非所有内容都显示在这里,因为它与问题无关。不,不是。如果它真的是-where?$aclRowLevel=$this->generate。。。正确的?请你把我要补充的内容准确地贴出来好吗。我是单元测试新手。好的,现在就看。调试($aclRowLevel->Auth);检查它是否真的被嘲笑了。它应该是一个模拟对象。你还可以比“不工作”更精确一点吗?Auth真的被嘲笑了,因为当我在我的控制器视图操作中放入$this->Auth->user('id')时,它确实工作(即返回值1)。但是组件中的$this->controller->Auth->user('id')不工作。