CodeIgniter 4 comes ready for PHPUnit testing. Tests live in the tests folder.
Run tests
composer test or vendor/bin/phpunit (on Windows: vendor\bin\phpunit).
Test classes
- Extend
CodeIgniter\Test\CIUnitTestCase FeatureTestTrait— call routes like a browser:$this->get('/'),$this->post('login', [...])DatabaseTestTrait— a test database, with$refresh = trueto run migrations fresh
Test database
Set the tests connection in .env (database.tests.database, etc.), or use SQLite in memory. Never point tests at your real database.
Useful assertions
assertOK(),assertStatus(404)assertSee('Welcome'),assertDontSee('Error')assertRedirectTo('/login')assertSessionHas('user_id')seeInDatabase('posts', ['title' => '...'])
Acting as a logged-in user
$this->withSession(['user_id' => 1])->get('dashboard').
Start with tests for login, your main forms and access rules.
Example
Example — Feature tests for posts
PHP
<?php
namespace Tests\Feature;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
class PostsTest extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
protected $refresh = true; // fresh migrations for each test class
public function testHomePageLoads(): void
{
$this->get('/')->assertOK();
}
public function testGuestIsRedirectedFromDashboard(): void
{
$this->get('dashboard')->assertRedirectTo('/login');
}
public function testLoggedInUserCanCreatePost(): void
{
$this->withSession(['user_id' => 1])
->post('posts', ['title' => 'Test post', 'body' => 'Hello'])
->assertRedirect();
$this->seeInDatabase('posts', ['title' => 'Test post']);
}
}
vendor/bin/phpunit runs the three tests and reports OK (3 tests). If someone breaks the auth filter later, testGuestIsRedirectedFromDashboard fails.