📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials CodeIgniter 4 Testing in CI4

Testing in CI4

6 min read Quiz at the end
Write CI4 feature tests with DatabaseTestTrait, FeatureTestTrait, withSession(), and seeInDatabase().

Testing in CI4

// tests/Feature/PostTest.php
use CodeIgniterTestCIUnitTestCase;
use CodeIgniterTestDatabaseTestTrait;
use CodeIgniterTestFeatureTestTrait;

class PostTest extends CIUnitTestCase {
    use DatabaseTestTrait, FeatureTestTrait;

    protected $migrate = true;
    protected $seed    = "TestSeeder";

    public function testGuestCannotCreatePost(): void {
        $result = $this->call("POST", "/posts", [
            "title" => "Test Post",
            "body"  => "Test body",
        ]);
        $result->assertStatus(302);
        $result->assertRedirectTo("/login");
    }

    public function testAuthUserCanCreatePost(): void {
        $this->withSession(["logged_in" => true, "user_id" => 1]);
        $result = $this->call("POST", "/posts", [
            "title" => "Test Post",
            "body"  => "Body content",
        ]);
        $result->assertStatus(302);
        $this->seeInDatabase("posts", ["title" => "Test Post"]);
    }
}

// Run
php spark test
Topic Quiz · 2 questions

Test your understanding before moving on

1. Which trait provides HTTP testing in CI4?
💡 CodeIgniterTestFeatureTestTrait provides $this->call() for simulating HTTP requests.
2. How do you simulate a session in CI4 tests?
💡 $this->withSession() sets session data for the simulated request.