【问题标题】:CakePHP unittest mocked Auth componentCakePHP unittest 模拟 Auth 组件
【发布时间】:2015-01-10 07:03:05
【问题描述】:

代码

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 方法“用户”不适用于来自组件的调用。因此,该查询中的用户 ID 的值为 null。

这应该怎么做?

【问题讨论】:

    标签: unit-testing cakephp mocking cakephp-2.0


    【解决方案1】:

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

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

    顺便说一句,checkUser() 中的代码应该进入模型。我也怀疑这根本不是一个组件。这个好像是用来授权的,为什么不making it a proper authorization adapter呢?

    【讨论】:

    • Auth 对象已经被模拟了?参见 $this->generate。这段代码在组件中是有原因的。此处并未显示所有内容,因为它与问题无关。
    • 不,不是。如果真的是——在哪里?
    • $AclRowLevels = $this->generate... 对吧?您能否准确地发布我应该添加的内容。我是单元测试新手。
    • 好的,现在看。调试($AclRowLevels->Auth);检查它是否真的被嘲笑。它应该是一个模拟对象。你也能比“不工作”更精确一点吗?
    • Auth 确实被嘲笑了,因为当我将 $this->Auth->user('id') 放在我的控制器视图操作中时,它确实有效(即返回值 1)。但是组件中的 $this->controller->Auth->user('id') 不起作用。
    【解决方案2】:

    这就是我要找的东西:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2011-07-31
      • 1970-01-01
      • 2021-04-12
      • 2011-09-09
      • 2011-05-09
      • 1970-01-01
      相关资源
      最近更新 更多