agyanadda@gmail.com

CodeIgniter 4 Testing

APIs and Advanced Topics 1 min read Updated Dec 3, 2026 Topic 28 of 30

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 = true to 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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which trait lets a test call routes with $this->get()?

Exercise 2 True / False

Tests should use a separate test database, not your real one.

Exercise 3 Fill in the Blank

Test classes extend CodeIgniter\Test\___TestCase

Frequently Asked Questions

No. Projects created with composer create-project codeigniter4/appstarter include PHPUnit as a development dependency, plus a phpunit.xml.dist file. Copy it to phpunit.xml to change settings.