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

我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.html

If 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错误


当然,我在这里遗漏了一些东西,但我不知道是什么。你能在这里帮我正确的方法吗?


莫回无
浏览 123回答 1
1回答

精慕HU

我在跑:PHP 7.3.9蛋糕PHP 2.10.16PHPUnit 5.7.27我通过模拟Session和Auth组件解决了这个问题。我在这样的测试中创建控制器setUp:<?phpApp::uses('CakeSession', 'Model/Datasource');class MyIntegrationTestCase extends ControllerTestCase{&nbsp; protected $ctrl;&nbsp; public function setUp()&nbsp; {&nbsp; &nbsp; parent::setUp();&nbsp; &nbsp; // https://api.cakephp.org/2.10/class-ControllerTestCase.html#_generate&nbsp; &nbsp; $mocks = [&nbsp; &nbsp; &nbsp; 'components' => [&nbsp; &nbsp; &nbsp; &nbsp; 'Session',&nbsp; &nbsp; &nbsp; &nbsp; 'Auth',&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; ];&nbsp; &nbsp; $this->ctrl = $this->generate('Quotes', $mocks);&nbsp; &nbsp; $user = [&nbsp; &nbsp; &nbsp; 'id' => 1,&nbsp; &nbsp; &nbsp; 'username' => 'alistaircol',&nbsp; &nbsp; ];&nbsp; &nbsp; CakeSession::write('Auth.User', $user);&nbsp; }}不能 100% 确定您是否需要Auth在项目中模拟组件,但没有这个我得到了 302。不知道这在我的项目中是否是非标准的。此外,您可能需要使用--stderr会话标志运行测试才能正常工作。
打开App,查看更多内容
随时随地看视频慕课网APP