This is an old revision of the document!
Testing controllers in CakePHP
Testing a controller at first seems and is very simple. You send a request to the same URL that you would open up in the browser and check things like view variables (variables that are given to the view through the controller), if the request got the correct response and sometimes if the action caused the correct result (like adding an entry or something like that).
It gets significantly harder when Authentication is implemented.
Authentication causes you to have to fake a login. Faking a login can be rather difficult as it requires:
- Having a fixture entry for a User with valid permissions
- Preparing session data by getting that certain entry from the test database
- Adding the whole user entity we got in the previous step to the session with an “Auth” prefix
Kinda looks like this:
[ // Superuser 'id' => 'dd137c92-9f03-4f0d-8e9a-0fba608ed373', 'username' => 'superadmin', 'password' => '$2y$10$tJek1ncybnTlHjEeyFh22umgK9c145mI5t8nMd05WIakA3CtsvTCu', 'active' => 1, 'is_superuser' => 1, 'created' => '2026-08-25 11:21:37', 'modified' => '2026-08-25 11:21:37', ],
protected function getSuperuserSessionData(): Entity { /** @var UsersTable $usersTable */ $usersTable = $this->getTableLocator()->get('Users'); $sessionData = $usersTable->find()->where(['id' => '<id of the user entry>'])->first(); return $sessionData; }
protected function loginAs($sessionData): void { if (!method_exists($this, 'session')) { throw new RuntimeException('No session component available'); } $this->session([ 'Auth' => $sessionData, ]); }
Only then can you request the controller like normal.
When controller actions include saving things, it makes sense to compare the expected value to the view variable and to the value that was saved to the database.
