Testing Your Application with PHPUnit
This guide adds automated tests to an application built from this template. At the end, one command runs all your tests:
composer testOK (7 tests, 12 assertions)These tests are what your CI pipeline will run on every push (see the CI/CD guide).
Which steps do you need?
- Your project was created from a recent version of this template (it already has a
tests/folder and aphpunit.xmlfile): skip to Step 7: Run the tests. - Your project has no
tests/folder: follow every step, in order. Each step gives the exact command or the complete file to create, and what you should see when it worked.
Before you start: check your project
Section titled “Before you start: check your project”Run every command in this guide in a terminal opened in your project’s root folder (the folder that contains composer.json). In VS Code, open a terminal with Ctrl+` .
- With Wampoon: run Composer as
.\composer.bat, as in the rest of this template’s README. Wampoon also prints “Wampoon Root Directory” and “PHP Path” lines before each command’s output; ignore them. - Without Wampoon: run
composerinstead of.\composer.bat.
Check the following before Step 1:
| Check | How | If not |
|---|---|---|
| PHP 8.2 or later | Run .\composer.bat --version. The second line shows the PHP version. | Update PHP (or Wampoon). |
config/bootstrap.php ends with return $app; | Open the file and look at the last lines. | The test setup in Step 4 needs this file to return the Slim App without running it. Compare your file with the template’s version ↗. |
config/env.php exists | Look in the config/ folder. | Copy config/env.example.php to config/env.php and fill in your database settings. |
| Your project is in Git | Run git status. | CI only works on a Git repository pushed to GitHub. |
Step 1: Install PHPUnit
Section titled “Step 1: Install PHPUnit”PHPUnit is the standard testing framework for PHP. Install it as a development dependency (--dev): it is needed to test the application, not to run it in production.
.\composer.bat require --dev "phpunit/phpunit:~11.5"Keep the quotes, and use ~11.5 exactly as written. It means “11.5 or any later 11.x version”. The more common ^11.5 does not work through composer.bat: Windows treats ^ as a special character and removes it, so Composer receives 11.5 and fails.
What you should see: among the last lines of the output, Generating autoload files and No security vulnerability advisories found. Your composer.json now ends with a "require-dev" section:
"require-dev": { "phpunit/phpunit": "~11.5" }If it fails:
phpunit/phpunit 11.5 (exact version match ...): the^was removed. Use~11.5, as above.requires php >=8.2: your PHP version is too old. See the checks above.
Step 2: Register the tests folder and the test command
Section titled “Step 2: Register the tests folder and the test command”Open composer.json and make two changes:
- Add an
autoload-devsection after the existingautoloadsection. It tells Composer that classes in theApp\Testsnamespace live in thetests/folder. - Add the line
"test": "@php phpunit",as the first line inside thescriptssection, with the comma at the end. It creates thecomposer testcommand. The@phpprefix makes Composer run PHPUnit with its own PHP, so the command works even whenphpis not on your PATH.
The relevant part of composer.json must look like this. The lines after "test" are the ones your file already had; keep them as they are:
"autoload": { "psr-4": { "App\\": "app/" } }, "autoload-dev": { "psr-4": { "App\\Tests\\": "tests/" } }, "scripts": { "test": "@php phpunit", "start": "php -S localhost:8080 -t public public/index.php", "post-create-project-cmd": [ "@php -r \"file_exists('config/env.php') || copy('config/env.example.php', 'config/env.php');\"" ] },Then rebuild Composer’s autoloader:
.\composer.bat dump-autoloadWhat you should see: Generated autoload files.
If it fails: "./composer.json" does not contain valid JSON: a comma is missing or extra. Each section ends with }, except the last one in the file, which ends with }.
Step 3: Create phpunit.xml
Section titled “Step 3: Create phpunit.xml”Create a file named phpunit.xml in your project’s root folder, with this content:
<?xml version="1.0" encoding="UTF-8"?><!-- PHPUnit configuration. Run the tests with: composer test --><phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="tests/bootstrap.php" cacheDirectory=".phpunit.cache" colors="true" failOnWarning="true" failOnRisky="true"> <testsuites> <!-- Tests of single classes and functions, without HTTP requests. --> <testsuite name="Unit"> <directory>tests/Unit</directory> </testsuite> <!-- Tests that send a request through the Slim app and check the response. --> <testsuite name="Http"> <directory>tests/Http</directory> </testsuite> </testsuites>
<php> <!-- Use the development settings (config/settings.dev.php). --> <env name="APP_ENV" value="dev" force="true"/> <!-- Empty base path, so tests request "/" instead of "/your-app-name/". --> <env name="APP_ROOT_DIR" value="" force="true"/> </php>
<source> <include> <directory>app</directory> </include> </source></phpunit>What each part does:
| Part | Purpose |
|---|---|
bootstrap="tests/bootstrap.php" | File that PHPUnit runs once, before any test. You create it in Step 4. |
failOnWarning="true" | A PHP warning during a test (for example, an undefined array key) fails the run instead of being ignored. |
<testsuite> | Two groups of tests, in two folders: tests/Unit and tests/Http. |
APP_ENV = dev | Loads the development settings, like your local site. |
APP_ROOT_DIR = empty | On Wampoon, your app lives at /your-app-name/. In tests, it lives at /, so a test requests /products, not /your-app-name/products. |
Also add the PHPUnit cache folder to .gitignore, if it is not there yet:
.phpunit.cache/Step 4: Create tests/bootstrap.php
Section titled “Step 4: Create tests/bootstrap.php”Create a tests/ folder in your project’s root folder, then create tests/bootstrap.php:
<?php
declare(strict_types=1);
/* * PHPUnit bootstrap: runs once, before any test. * * It creates the Slim application a single time and shares it with every test, * because config/bootstrap.php cannot be loaded twice in the same PHP process * (it declares global functions and constants). */
use App\Helpers\Core\AppSettings;use App\Tests\TestCase;
require __DIR__ . '/../vendor/autoload.php';
// The application stops if config/env.php is missing, so give a clear message instead.if (!file_exists(__DIR__ . '/../config/env.php')) { fwrite(STDERR, "config/env.php not found. Copy config/env.example.php to config/env.php, then run the tests again.\n"); exit(1);}
// Create the Slim application, exactly as public/index.php does (without running it).$app = require __DIR__ . '/../config/bootstrap.php';
// Load the settings now: config/defaults.php installs an error handler that prints// errors as HTML. Remove it, so PHPUnit can report warnings and errors itself.$app->getContainer()->get(AppSettings::class);restore_error_handler();
TestCase::setApp($app);Why this file is needed:
- The app is created once.
config/bootstrap.phpdeclares global functions such ashs(). Loading it a second time stops PHP with “Cannot redeclare function hs()”. Every test therefore shares the same application. config/env.phpmust exist. Without it, the application stops before any test runs. The check above explains what to do instead of failing silently.- The template’s error handler is removed. It prints errors as HTML, which would hide them from PHPUnit.
Step 5: Create tests/TestCase.php
Section titled “Step 5: Create tests/TestCase.php”Create tests/TestCase.php. Your HTTP tests extend this class: it gives them get() and request() methods that send a request to your application and return the response.
<?php
declare(strict_types=1);
namespace App\Tests;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;use Psr\Http\Message\ResponseInterface;use Slim\App;use Slim\Psr7\Factory\ServerRequestFactory;
/** * Base class for the tests of this application. * * Extend it instead of PHPUnit's TestCase to send requests to the Slim app: * * $response = $this->get('/'); * $this->assertSame(200, $response->getStatusCode()); */abstract class TestCase extends PHPUnitTestCase{ private static ?App $app = null;
/** * Store the application created in tests/bootstrap.php. */ public static function setApp(App $app): void { self::$app = $app; }
/** * Start every test with an empty session, so that data stored by one test * (a logged-in user, a flash message, a cart) cannot affect the next one. */ protected function setUp(): void { parent::setUp(); $_SESSION = []; }
/** * Return the application shared by all tests. */ protected function app(): App { if (self::$app === null) { self::fail('The application was not created. Check that phpunit.xml uses tests/bootstrap.php.'); }
return self::$app; }
/** * Send a request to the application and return its response. * * @param array<string, string> $formData Form fields for POST requests. */ protected function request(string $method, string $path, array $formData = []): ResponseInterface { $request = (new ServerRequestFactory())->createServerRequest($method, $path);
if ($formData !== []) { $request = $request->withParsedBody($formData); }
return $this->app()->handle($request); }
/** * Send a GET request to the application and return its response. */ protected function get(string $path): ResponseInterface { return $this->request('GET', $path); }}Step 6: Write your first tests
Section titled “Step 6: Write your first tests”Create two folders: tests/Unit and tests/Http.
A unit test
Section titled “A unit test”A unit test checks one class or function on its own, without HTTP requests or a database. Create tests/Unit/ResultTest.php, which tests the template’s Result class (app/Helpers/Core/Result.php):
<?php
declare(strict_types=1);
namespace App\Tests\Unit;
use App\Helpers\Core\Result;use App\Helpers\Core\ResultDataException;use InvalidArgumentException;use PHPUnit\Framework\Attributes\Test;use PHPUnit\Framework\TestCase;
/** * Unit tests for the Result class (app/Helpers/Core/Result.php). * * A unit test checks one class on its own: no HTTP request and no database. * Each test follows the Arrange-Act-Assert pattern. */final class ResultTest extends TestCase{ #[Test] public function successResultHoldsItsMessageAndData(): void { // Arrange and act: create a successful result. $result = Result::success('Product saved.', ['id' => 7]);
// Assert: check what the result reports. $this->assertTrue($result->isSuccess()); $this->assertFalse($result->isFailure()); $this->assertSame('Product saved.', $result->getMessage()); $this->assertSame(['id' => 7], $result->getData()); }
#[Test] public function failureResultHoldsItsErrors(): void { $result = Result::failure('Validation failed.', ['name' => 'The name is required.']);
$this->assertTrue($result->isFailure()); $this->assertSame(['name' => 'The name is required.'], $result->getErrors()); }
#[Test] public function readingDataFromFailureThrowsAnException(): void { $result = Result::failure('Validation failed.');
// Tell PHPUnit which exception the next line must throw. $this->expectException(ResultDataException::class);
$result->getData(); }
#[Test] public function emptyMessageIsRejected(): void { $this->expectException(InvalidArgumentException::class);
Result::success(' '); }}How to read it:
- The class name ends with
Test, and its file name matches the class name. - Each test is a public method marked with
#[Test]. assertSame($expected, $actual)fails the test when the two values differ.expectException()fails the test when the code after it does not throw that exception.
An HTTP test
Section titled “An HTTP test”An HTTP test sends a request through your whole application (routes, middleware, controller, view) and checks the response, without a browser or Apache. Create tests/Http/RoutesTest.php:
<?php
declare(strict_types=1);
namespace App\Tests\Http;
use App\Tests\TestCase;use PHPUnit\Framework\Attributes\Test;
/** * HTTP tests: each test sends a request through the whole Slim application * (routes, middleware, controller, view) and checks the response. */final class RoutesTest extends TestCase{ #[Test] public function homePageLoads(): void { $response = $this->get('/');
$this->assertSame(200, $response->getStatusCode()); $this->assertStringContainsString( 'Slim Framework-based MVC Application', (string) $response->getBody() ); }
#[Test] public function unknownPageReturns404(): void { $response = $this->get('/this-page-does-not-exist');
$this->assertSame(404, $response->getStatusCode()); }
#[Test] public function errorRouteReturns400(): void { $response = $this->get('/error');
$this->assertSame(400, $response->getStatusCode()); }}This class extends your App\Tests\TestCase (Step 5), not PHPUnit’s, so it can call $this->get().
Adapt it to your project:
homePageLoads()looks for the heading of the template’s home page. If you changed your home page, replace'Slim Framework-based MVC Application'with a text that appears on yours.- If you removed the template’s
/errorroute, deleteerrorRouteReturns400().
Step 7: Run the tests
Section titled “Step 7: Run the tests”.\composer.bat testWhat you should see:
PHPUnit 11.5.58 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.1Configuration: C:\Wampoon\htdocs\your-app-name\phpunit.xml
....... 7 / 7 (100%)
Time: 00:00.512, Memory: 10.00 MB
OK (7 tests, 12 assertions)Each dot is a passing test. The version numbers and the time can differ. A project created from a recent version of the template also has tests/Unit/HelpersTest.php, so it shows OK (10 tests, 16 assertions).
If it fails: 'php' is not recognized as an internal or external command: the test script in composer.json is missing @php. It must read "test": "@php phpunit",, as in Step 2.
Check that a failing test is detected. In RoutesTest.php, change 404 to 200 in unknownPageReturns404(), and run the tests again. You should see F instead of a dot, the message Failed asserting that 404 is identical to 200., and FAILURES!. Change it back to 404. This is exactly what your CI pipeline will detect.
To run only one group or one file:
.\composer.bat test -- --testsuite Unit.\composer.bat test -- tests/Http/RoutesTest.phpWriting tests for your own code
Section titled “Writing tests for your own code”Where each test goes
Section titled “Where each test goes”| You want to test… | Test type | Folder | Extends |
|---|---|---|---|
| A helper or a class that needs no database (validation, calculations, formatting) | Unit | tests/Unit | PHPUnit\Framework\TestCase |
| A page or a form: status code, redirect, text on the page | HTTP | tests/Http | App\Tests\TestCase |
| A model’s queries | Database | tests/Database | See Testing your models |
From user stories to tests
Section titled “From user stories to tests”The story tests you wrote for your user stories (GIVEN, WHEN, THEN) translate directly into tests: GIVEN is the Arrange part, WHEN is the Act part, and THEN is the Assert part.
For example, take this story test:
GIVEN a visitor who is not logged in, WHEN they open the admin dashboard, THEN they are redirected to the login page.
It becomes:
#[Test]public function visitorIsRedirectedToLoginFromAdminDashboard(): void{ // GIVEN (Arrange): a visitor who is not logged in. // setUp() already empties the session.
// WHEN (Act): they open the admin dashboard. $response = $this->get('/admin/dashboard');
// THEN (Assert): they are redirected to the login page. $this->assertSame(302, $response->getStatusCode()); $this->assertStringEndsWith('/login', $response->getHeaderLine('Location'));}The routes in this example (/admin/dashboard, /login) are examples: use the routes of your own application.
To submit a form, use request() with the form fields:
$response = $this->request('POST', '/login', [ 'identifier' => 'customer@example.com', 'password' => 'wrong-password',]);Testing your models
Section titled “Testing your models”Model tests need a database. Run them against your local database, but wrap each test in a transaction that is rolled back afterwards, so the test leaves no data behind. Create tests/DatabaseTestCase.php:
<?php
declare(strict_types=1);
namespace App\Tests;
use App\Helpers\Core\PDOService;use PDO;
/** * Base class for tests that use the database. * * Each test runs inside a transaction that is rolled back at the end, * so the database is left exactly as it was. */abstract class DatabaseTestCase extends TestCase{ protected PDO $pdo;
protected function setUp(): void { parent::setUp(); // The same connection as your models: the container creates PDOService once. $this->pdo = $this->app()->getContainer()->get(PDOService::class)->getPDO(); $this->pdo->beginTransaction(); }
protected function tearDown(): void { if ($this->pdo->inTransaction()) { $this->pdo->rollBack(); } parent::tearDown(); }}Then add a Database test suite to phpunit.xml, after the Http one:
<testsuite name="Database"> <directory>tests/Database</directory> </testsuite>An example model test, tests/Database/ProductsModelTest.php (use your own model and columns):
<?php
declare(strict_types=1);
namespace App\Tests\Database;
use App\Domain\Models\ProductsModel;use App\Tests\DatabaseTestCase;use PHPUnit\Framework\Attributes\Test;
final class ProductsModelTest extends DatabaseTestCase{ #[Test] public function newProductCanBeFoundById(): void { $model = $this->app()->getContainer()->get(ProductsModel::class);
$id = (int) $model->createAndGetId([ 'category_id' => 1, 'name' => 'Test product', 'price' => 9.99, 'description' => 'Created by a test', ]);
$product = $model->findById($id);
$this->assertSame('Test product', $product['name']); }}Database tests connect with the same settings as your site, from config/env.php. If your site works in the browser, your tests can reach the database too.
Two limits to know:
- Database tests need the database server to be running (start MariaDB in Wampoon first). In CI, the pipeline starts its own database server: see Adding a database for model tests in the CI/CD guide.
- The rollback only undoes data changes in InnoDB tables (MariaDB’s default).
CREATE TABLE,ALTER TABLE, andTRUNCATEcannot be rolled back, so do not run them in tests.
Troubleshooting
Section titled “Troubleshooting”| Message | Cause | Fix |
|---|---|---|
config/env.php not found | The file is missing. | Copy config/env.example.php to config/env.php. |
Cannot redeclare function hs() | Something loads config/bootstrap.php a second time, for example a test that requires it. | Only tests/bootstrap.php may load it. Use $this->app() in your tests. |
Class "App\Tests\TestCase" not found | The autoload-dev section is missing, or the autoloader was not rebuilt. | Check Step 2, then run .\composer.bat dump-autoload. |
An HTTP test gets a 404 for a page that works in the browser | The test includes your app’s folder name in the path. | Request /products, not /your-app-name/products (APP_ROOT_DIR is empty in tests). |
| The page in an HTTP test has no header or footer | The views load the layout with require_once, so only the first page rendered during a test run gets it. | Check text inside the page itself, not the <title> or the navigation bar. |
No tests executed! | The file or method names do not match what PHPUnit looks for. | File names must end with Test.php, and each test method needs #[Test]. |
SQLSTATE[HY000] [2002] in a database test | The database server is not running, or config/env.php uses the wrong port. Wampoon’s MariaDB listens on port 3307, not the usual 3306. | Start MariaDB. Check that config/env.php contains $settings['db']['port'] = '3307'; when you use Wampoon. To skip the database tests: .\composer.bat test -- --testsuite Unit. |