2

I'm getting Static method "user" cannot be invoked on mock object even did not mock auth->user.

Im using php7, cakephp2.x and phpunit4+ According to cakephp2 documentation :

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.

I tried using :

$user = [
  'id' => 1,
  'username' => 'mark'
];

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

But when calling :

$user = $this->Controller->Auth->user();

Im still getting : Static method "user" cannot be invoked on mock object error

Surely i'm missing something here but I don't know what. could you please help me the correct approach here.

Thank you

monn
  • 23
  • 4

1 Answers1

1

I'm running:

  • PHP 7.3.9
  • CakePHP 2.10.16
  • PHPUnit 5.7.27

I solved this by mocking the Session and Auth component. I'm creating the controller in the tests setUp like this:

<?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);
  }
}

Not 100% certain whether you need to mock Auth component in your project, but I got 302 without this. Don't know if this is something non-standard in my project.

Also, you might need to run the test with the --stderr flag for session to work correctly.

References:

alistaircol
  • 1,433
  • 12
  • 22