Write unit test for a controller that uses AuthComponent in CakePHP 2

I am trying to test the action of a controller that allows user profiles to be released. Among other things, I want to check that each registered user can edit his profile, and not another. In case of violation of this restriction, the action should be redirected to the predefined home page.

In this scenario, I have a device that creates a user with ID = 1. Therefore, I thought about testing the constraint this way:

$data = $this->Users->User->read(null, 1); 
$this->Users->Auth->login($data); 
$this->testAction('/users/edit/2', array('method' => 'get')); 
$url = parse_url($this->headers['Location']); 
$this->assertEquals($url['path'], '/homepage'); 

The test passes this statement. So, the next step is to verify the execution '/users/edit/1', which has a registered user ID, shows the form:

$this->testAction('/users/edit/1', array('method' => 'get', 'return' => 'vars'));
$matcher = array( 
  'tag' => 'form', 
  'ancestor' => array('tag' => 'div'), 
  'descendant' => array('tag' => 'fieldset'), 
); 
$this->assertTag($matcher, $this->vars['content_for_layout'], 'The edition form was not found');

. debug() , $this->Auth->user() , $this->Auth->user('id') null. , test to fail.

, , . , ?

!

+5
5

mock- :

$this->controller = $this->generate('Users', array(
    'components' => array('Auth' => array('user')) //We mock the Auth Component here
));
$this->controller->Auth->staticExpects($this->once())->method('user') //The method user()
    ->with('id') //Will be called with first param 'id'
    ->will($this->returnValue(2)) //And will return something for me
$this->testAction('/users/edit/2', array('method' => 'get')); 

mocks - ,

11 2015 .

AuthComponent

$this->controller = $this->generate('Users', array(
    'components' => array('Auth') // Mock all Auth methods
));
+5

, , , AuthComponent Session , .

, , isAuthorized() . MyController:: isAuthorized(). , mocks.

, , TestCase:: generate() , Mark Story CakePHP mock, CakePHP AuthComponent.

. . testIsAuthorized() def MockAnnouncementsController .

, CakePHP , requestAction(). , Controller:: isAuthorized() AuthComponent , , , . , , , (, "index", "view" ), , , , , .

+1

:

$this->Auth->user('id')

:

$this->Auth->data['User']['id']
$this->Session->read('Auth.User.id')
0

:

$this->Users->Session->write('Auth.User', 
    array('id' => 1,'and_other_fields_you_need' => 'whatever')
);  
0

Mark Story gives me an answer on a CakePHP ticket . Basically, I have to register the user as follows:

$data = $this->Users->User->read(null, 1); 
$this->Users->Auth->login($data['User']);

instead

$data = $this->Users->User->read(null, 1); 
$this->Users->Auth->login($data);
0
source

All Articles