PHPUnit CakePHP 4.X - mock up the identity object, but how?

i written a webaplication with cakephp 4.x. In my controller(AppController.php) i have implements the following:

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

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


Now i written the phpunit test following:

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->assertSession(1, ''); //check if the user is logged in

But my identity object is allways empty. empty identity object

The object should actually look like this: the original object with data

i have no more ideas how to implement it. Can someone help me? :slight_smile:

I’m not 100% sure but I don’t think the modern Authentication middleware uses Auth.User as it’s identity key. It might be just Auth now. You can easily check.

This is a working test suite user login on a 4.x app with Authentication middleware and the new (and awesome) fixture factories:

    public function login($role, $keyId = null)
        $person = PersonFactory::make()
            ->makeActor($role, $keyId);
        $user = TableRegistry::getTableLocator()
            ->get($person->user->id, ['contain' => ['People']]);
        $this->session(['Auth' => $user]);

Instead of setting session key to Auth.User use Auth key only:

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

To review the session array you can debug $this->_requestSession property.

1 Like

Thanks @bizdev
You have helped me a lot. :slight_smile: