After this lesson you can run repeatable feature tests against a test database and explain what a passing assertion proves. Tests are useful when they check behavior that matters: a page lists known data, an unknown record is handled and untrusted title text is escaped.
Give tests their own state
The ordinary local database changes as you practise forms. Tests should not depend on that history. CodeIgniter's DatabaseTestTrait can prepare schema and seeded data for the test lifecycle. Preserve the starter's tests connection and testing-environment behavior instead of pointing tests at the ordinary bookshop SQLite file.
Create tests/feature/CatalogueTest.php with this class. The application migration and BookSeeder must already exist. The namespace setting tells database preparation to include the application migrations.
<?php
namespace Tests\Feature;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;
class CatalogueTest extends CIUnitTestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
protected $namespace = 'App';
protected $seed = 'App\Database\Seeds\BookSeeder';
public function testCatalogueListsSeededBooks(): void
{
$result = $this->get('books');
$result->assertStatus(200);
$result->assertSee('The Paper Orchard');
}
public function testApiReturnsBook(): void
{
$result = $this->get('api/books/1');
$result->assertStatus(200);
$result->assertJSONFragment(['title' => 'The Paper Orchard']);
}
public function testMissingApiBook(): void
{
$this->get('api/books/999')->assertStatus(404);
}
public function testUnknownHtmlBook(): void
{
$this->expectException(\CodeIgniter\Exceptions\PageNotFoundException::class);
$this->get('books/999');
}
public function testTitleIsEscaped(): void
{
(new \App\Models\BookModel())->insert(['title' => '<script>alert(1)</script>']);
$result = $this->get('books');
$this->assertStringContainsString('<script>', $result->response()->getBody());
$this->assertStringNotContainsString('<script>alert(1)</script>', $result->response()->getBody());
}
public function testReadOnlyFilter(): void
{
$this->get('maintenance-example')->assertStatus(403);
}
}This exact class was run against CodeIgniter 4.7.6. It checks the normal list, API success, missing records, escaped title output and the deny-all demonstration filter. The test that expects a missing HTML book uses expectException because this test lifecycle surfaces PageNotFoundException; direct HTTP verification separately confirmed the rendered 404 response.
Read assertions as claims
The escaped-title test inserts markup-looking text into the test database and inspects the rendered body. It checks both presence of encoded text and absence of the raw script fragment. That is a useful regression check for this particular rendering location. It does not prove that every template and every output context in the application is safe.
The API test checks a JSON fragment rather than the exact byte order of every key. This keeps the assertion focused on the data contract. A test that insists on timestamps, generated paths or unrelated formatting would fail for changes that do not affect the intended behavior.
Run the focused suite
vendor/bin/phpunit --no-coverage --filter CatalogueTestExample output captured on 2026-11; yours will differ. Timing, memory, configuration paths and the progress line are omitted.
PHPUnit 10.5.67 by Sebastian Bergmann and contributors.
Runtime: PHP 8.4.24
OK (6 tests, 10 assertions)The no-coverage flag avoids requesting code coverage in a workspace without a coverage driver. It does not skip the assertions. The default starter run initially warned about missing coverage support; the focused command above completed without that warning.
Coverage and correctness are different questions. Executing a line is not proof that the application enforces a meaningful rule. Prefer assertions about accepted and rejected behavior rather than adding tests that merely mirror the code's current implementation.
Separate action tests from policy tests
The optional API-input verification used test-only routes to invoke its otherwise unexposed create method. Four additional cases checked accepted input, missing title, malformed JSON and an array body. Those checks returned the expected 201 or 400 statuses. They did not exercise an authentication integration or the production route surface.
For real write policies, test both the response and unchanged data after rejection. For uploads, inspect private storage effects. For CSRF, use an appropriate request flow and inspect redirects rather than treating a final page status as the original submission status. Different tests can cover different layers, provided their limits remain clear.
Diagnose failures instead of weakening them
If a missing-book test throws an exception, understand the test lifecycle before changing the controller to hide every error. If an escaping assertion fails, inspect the raw response body and the assertion's semantics. During verification, a DOM-oriented assertion argument was unsuitable for checking raw markup, so the final test uses explicit string assertions on the body.
The fetched official Testing overview and HTTP Feature Testing guide document the test facilities. The class above is original bookshop verification code and does not access this repository's database.
Common mistakes
Reusing persistent learning data makes tests order-dependent. Replacing a meaningful failure expectation with an unconditional success hides regressions. Treating an action test as proof of all filters overstates coverage. Finally, asserting a whole response including incidental paths or times makes tests brittle without strengthening the behavior contract.
Exercise
Explain why the escaping test writes through BookModel before requesting the catalogue. Then identify one additional assertion needed before claiming that a denied update cannot change a stored title.
Show an answer
Writing the test record exercises the complete stored-data rendering path rather than only calling an escaping helper. A denied-update test should read the record afterward and compare its title with the original value. A denial status alone does not establish that no mutation happened before the response.
Previous lesson · Next lesson · Related: explicit routes · Related: security boundaries
Key points
- Tests prepare a separate known database state.
- The catalogue suite passed six tests and ten assertions.
- A passing action test proves only the boundaries it actually exercises.