CakePHP unittest模拟了Auth组件

时间:2015-01-09 11:45:26

标签: 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() {
        $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组件中的查询需要Auth用户ID。我想模拟user_id值' 1'用于单元测试。 模拟的Auth方法'用户'在我的测试中不适用于来自组件的调用。因此该查询中的用户标识值为null。

应该怎么做?

2 个答案:

答案 0 :(得分:0)

执行debug($AclRowLevels->Auth);检查是否真的被嘲笑了。它应该是一个模拟对象。如果不是出于某种原因尝试:

$AclRowLevels->Auth = $this->getMock(/*...*/);

checkUser()中的代码应该顺便进入模型。我也怀疑这必须是一个组成部分。这似乎是用于授权,所以为什么不making it a proper authorization adapter

答案 1 :(得分:0)

这就是我想要的:

    $AclRowLevels->Auth
        ->staticExpects($this->any())
        ->method('user')
        ->will($this->returnCallback(
            function($arg) {
                if ($arg === 'id') {
                    return 1;
                }
                return null;
            }
        ));