【问题标题】:PHPUnit CakePHP 4.X - mock up the identity object, but how? [closed]PHPUnit CakePHP 4.X - 模拟身份对象,但如何? [关闭]
【发布时间】:2020-10-15 12:18:08
【问题描述】:

我用 cakephp 4.x 编写了一个 webaplication。在我的控制器(AppController.php)中,我实现了以下内容:

...
public function beforeRender(\Cake\Event\EventInterface  $event)
{

    #Load User_ID
    if($this->Authentication->getIdentity()){
        $identity = $this->Authentication->getIdentity();
        $user_id = $this->Authentication->getIdentity()->getIdentifier();
    } 

}
...

现在我编写了以下 phpunit 测试:

...
private function loginAsAdmin() {
    $this->Users = TableRegistry::getTableLocator()->get('Users');
    $user = $this->Users->get(1);
    $this->session(['Auth.User'=> $user->toArray()]);
}
/**
 * Test loginAsUser method
 *
 * @return void
 */
public function testLoginAsAdmin(): void
{
    $this->loginAsAdmin();
    
    $this->get('/admin/dashboard');
    
    $this->assertSession(1, 'Auth.User.id'); //check if the user is logged in
}
...

但我的身份对象总是空的。

对象实际上应该是这样的:

我没有更多的想法如何实现它。有人能帮我吗? :)

【问题讨论】:

    标签: php authentication cakephp phpunit cakephp-4.x


    【解决方案1】:

    使用身份验证插件,用户默认存储为对象,如果您传递的对象不是实现\ArrayAccess 的对象,那么身份验证服务会将给定数据包装在\ArrayObject 的实例中。

    此外,数据默认存储在Auth 键,而不是Auth.User

    理论上传递数组数据也应该有效(如“被视为经过身份验证并在身份对象中设置数据”),即使嵌套在附加键中(除非您为会话启用了identify 选项验证器),所以可能在您的代码中的某个地方存在其他问题,数组对象中有 storage_config 之类的键真的很奇怪,这不应该在开箱即用的设置中发生。

    无论如何,通常你会像这样使用身份验证进行测试:

    $user = $this->Users->get(1);
    $this->session(['Auth' => $user]);
    

    另见

    【讨论】:

    • 感谢@ndm 的帮助。真的很感激。我还为您的回答添加了投票。 :)
    猜你喜欢
    • 2021-02-10
    • 2021-12-31
    • 2017-01-25
    • 2014-08-23
    • 2021-10-31
    • 2012-09-26
    • 1970-01-01
    • 2012-05-05
    • 2014-11-14
    相关资源
    最近更新 更多