为了账号安全,请及时绑定邮箱和手机立即绑定

如何修复 cakephp 2 和 phpunit4 中的模拟身份验证错误?

如何修复 cakephp 2 和 phpunit4 中的模拟身份验证错误?

PHP
莫回无 2021-11-19 15:24:05
我Static method "user" cannot be invoked on mock object什至没有嘲笑auth->user。我使用 php7、cakephp2.x 和 phpunit4+ 根据 cakephp2 文档:https://book.cakephp.org/2.0/en/development/testing.htmlIf you are using PHPUnit 4 or 5, staticExpects() does not exist anymore. Instead, you should insert the necessary data into the session with CakeSession::write('Auth.User', $user) before calling the action.我尝试使用:$user = [  'id' => 1,  'username' => 'mark'];CakeSession::write('Auth.User', $user);但是在调用时:$user = $this->Controller->Auth->user();我仍然收到: Static method "user" cannot be invoked on mock object错误当然,我在这里遗漏了一些东西,但我不知道是什么。你能在这里帮我正确的方法吗?
查看完整描述

1 回答

?
精慕HU

TA贡献1845条经验 获得超8个赞

我在跑:

  • PHP 7.3.9

  • 蛋糕PHP 2.10.16

  • PHPUnit 5.7.27

我通过模拟SessionAuth组件解决了这个问题。我在这样的测试中创建控制器setUp

<?php

App::uses('CakeSession', 'Model/Datasource');


class MyIntegrationTestCase extends ControllerTestCase

{

  protected $ctrl;


  public function setUp()

  {

    parent::setUp();


    // https://api.cakephp.org/2.10/class-ControllerTestCase.html#_generate

    $mocks = [

      'components' => [

        'Session',

        'Auth',

      ]

    ];

    $this->ctrl = $this->generate('Quotes', $mocks);


    $user = [

      'id' => 1,

      'username' => 'alistaircol',

    ];

    CakeSession::write('Auth.User', $user);

  }

}

不能 100% 确定您是否需要Auth在项目中模拟组件,但没有这个我得到了 302。不知道这在我的项目中是否是非标准的。


此外,您可能需要使用--stderr会话标志运行测试才能正常工作。



查看完整回答
反对 回复 2021-11-19
  • 1 回答
  • 0 关注
  • 122 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信