Objectives and prerequisites
By the end of this course, you will be able to choose useful tests, write robust unit and integration tests, replace external dependencies, measure quality and wire a continuous integration pipeline. The common thread is the Mdjad catalogue cart, enriched and secured step by step.
Prerequisites: write object-oriented PHP and know basic PHPUnit (courses F03 and F04). Examples use PHP 8.4, PHPUnit 13, Symfony 7.4 and an isolated test database. Commands run from the project root.
Path: chapters 1 to 3 establish strategy, unit tests and doubles; chapters 4 and 5 cover integration and functional tests; chapters 6 to 8 cover TDD, metrics and CI; chapters 9 and 10 cover data and synthesis.
Convention: a test describes observable behaviour, not implementation. Examples are deliberately small. No test depends on a production database or a real external service. Test names are in English, following the project convention.
1. What a test is for, and which one to write
An automated test verifies that an expected behaviour occurs and fails when it stops occurring. It prevents regressions, documents the contract and makes refactoring possible. A test that cannot fail adds nothing; a test that breaks on every implementation change is a burden.
The test pyramid places many fast unit tests, fewer integration tests and few end-to-end tests. This distribution is not a law: it balances speed, confidence and maintenance cost. A domain rich in rules deserves unit tests; a complex SQL query deserves an integration test.
Unit test : fast, isolated, one business rule
Integration test : several components, database or HTTP
Functional test : user journey through the framework
E2E test : real browser, end to end, slower
Choose the lowest test that covers the risk. Testing a discount rule through a browser is slow and fragile; a unit test is enough. Testing that a migration creates the right column through a unit test is impossible; an integration test is necessary.
A test must be deterministic: same inputs, same result, without depending on time, randomness, execution order or network. Time and randomness are injected or frozen. A flaky test is worse than no test because it teaches people to ignore failures.
Finally, measure risk. A critical feature, a financial calculation, an authorisation or a migration deserves strong coverage. A simple getter or a template without logic deserves little testing. Coverage should follow risk, not line count.
2. Unit tests: structure and assertions
A unit test isolates one unit of behaviour. Arrange-act-assert prepares data, performs the action, then verifies the result. The test name describes the rule and case: testTotalIsZeroForEmptyCart. A name like testCart teaches nothing.
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
final class MoneyTest extends TestCase
{
public function testAddsTwoAmountsInCents(): void
{
$total = Money::fromCents(1250)->add(Money::fromCents(350));
self::assertSame(1600, $total->cents);
}
public function testRejectsNegativeAmount(): void
{
$this->expectException(InvalidArgumentException::class);
Money::fromCents(-1);
}
}
Prefer assertSame to assertEquals when the type matters. assertSame compares value and type; assertEquals applies a looser equality. For an array, assertSame checks order and types; assertEquals can hide a difference.
Test nominal cases, boundaries and errors. For a discount, test 0%, 100%, an invalid percentage and a zero total. For a quantity, test 1, 0, -1 and an addition. Boundaries reveal comparison errors and division by zero.
use PHPUnit\Framework\Attributes\DataProvider;
final class DiscountTest extends TestCase
{
#[DataProvider('invalidPercentages')]
public function testRejectsInvalidPercentage(int $percent): void
{
$this->expectException(InvalidArgumentException::class);
new PercentageDiscount($percent);
}
public static function invalidPercentages(): iterable
{
yield 'negative' => [-1];
yield 'above one hundred' => [101];
}
}
A data provider reduces duplication without hiding the case. Each dataset needs a readable name. Avoid generic tests that loop over twenty cases without explaining the expectation; a failure must be immediately understandable.
Finally, do not test private details. A test that calls a private method through reflection couples the test to the implementation. Test public behaviour, then extract a class if a detail deserves its own contract. The test must survive an internal refactoring.
3. Doubles: stubs, fakes and mocks
A double replaces a dependency to isolate the unit. A stub returns a prepared value. A fake is a simplified but working implementation, such as a fixed clock. A mock verifies that an interaction occurred. Choose the simplest double that expresses the need.
interface Clock
{
public function now(): DateTimeImmutable;
}
final class FixedClock implements Clock
{
public function __construct(private DateTimeImmutable $date)
{
}
public function now(): DateTimeImmutable
{
return $this->date;
}
}
final class ExpirationPolicy
{
public function __construct(private Clock $clock)
{
}
public function isExpired(DateTimeImmutable $createdAt): bool
{
return $this->clock->now()->diff($createdAt)->days > 30;
}
}
The FixedClock fake makes the test deterministic without a mocking framework. It is readable and reusable. For a complex dependency, a mock can verify a precise call, but it couples the test to the protocol. Prefer verifying the observable result when possible.
Do not mock value objects or collections you control. A real Money is simpler than a mock of Money. Do not mock the subject under test either: you would test the mock, not the code. Doubles serve boundaries: time, network, database, files, external service.
Dependency injection makes doubles possible. A class that creates its own clock or HTTP client is hard to test. Receive the dependency in the constructor, with a safe default if optional. The test becomes a simple composition.
Finally, verify collaborations sparingly. A test that checks three internal calls breaks on the slightest refactoring. Verify the effect instead: the message sent, the total computed, the state saved. Interaction mocks are useful for side effects that cannot be observed otherwise.
4. Integration tests: database, files and HTTP
An integration test verifies several components together: a repository and a database, a controller and the container, an HTTP client and a simulated server. It is slower than a unit test but covers the seams the unit cannot see: mapping, SQL, serialisation, configuration.
final class CartRepositoryTest extends KernelTestCase
{
use ResetDatabase;
public function testPersistsAndReadsCart(): void
{
self::bootKernel();
$em = self::getContainer()->get(EntityManagerInterface::class);
$cart = new Cart();
$cart->add(ProductFactory::createOne(), 2);
$em->persist($cart);
$em->flush();
$em->clear();
$found = $em->getRepository(Cart::class)->find($cart->getId());
self::assertNotNull($found);
self::assertCount(1, $found->items());
}
}
A test database must be isolated from production and reset between tests or suites. Transactions with rollback are fast but do not cover real commits. Migrations must be applied to an empty database to verify they work.
For files, use a temporary directory and clean it. For external services, use a simulated server or a fake client. A test that calls a real API depends on network, quota and provider data. It is slow and non-deterministic.
Symfony functional tests use WebTestCase and an internal HTTP client. They verify status, content, redirects and forms. They do not prove visual rendering or JavaScript; a browser test complements these aspects.
final class CatalogControllerTest extends WebTestCase
{
public function testCatalogPageIsPublic(): void
{
$client = self::createClient();
$client->request('GET', '/fr/tutoriels');
self::assertResponseIsSuccessful();
self::assertSelectorExists('.learning-card');
}
}
Finally, an integration test must remain readable. If setup is long, extract a factory or helper. The test must clearly show what is tested, not only how the database is filled.
5. Functional, end-to-end and flakiness
A functional test goes through the framework: route, controller, form, template, database. It verifies a user journey. An E2E test drives a real browser: clicks, input, navigation, JavaScript. It is closest to the user and slowest.
Reserve E2E for critical journeys: login, purchase, payment, registration, a major error path. Testing every text variant in a browser is expensive. Functional tests cover most journeys; E2E verifies real browser integration.
Catalogue E2E journey:
1. open the home page
2. search for "notebook"
3. check the result count
4. add a product to the cart
5. check the total and the accessible message
Flakiness often comes from arbitrary waits (sleep), fragile selectors, shared data, test order or animation. Wait for an observable condition, use stable selectors such as data-testid, isolate data and avoid dependencies between tests.
A test that fails intermittently must be fixed or removed, not marked "known". It hides real bugs and destroys trust. If a test depends on time, inject a clock. If it depends on the network, simulate. If it depends on order, isolate.
Finally, an E2E test must produce evidence on failure: screenshot, trace, logs. Without evidence, diagnosis becomes an investigation. Storage cost is small compared with the time lost reproducing a non-reproducible failure.
6. TDD: designing through tests
Test-driven development follows a short cycle: write a failing test, write the minimum to make it pass, then refactor. The test describes behaviour before the code. The cycle forces contract clarification and keeps steps small.
Red : write a failing test for a missing rule
Green : write the simplest code that passes
Refactor: improve the code without changing behaviour
TDD is not a religious obligation. It is especially useful for business rules, algorithms and bug fixes: reproduce the bug with a test, then fix it. For UI exploration or a mock-up, it may be too early.
A bug must first be reproduced by a failing test. Without that test, the fix may be incomplete and the bug may return. The regression test documents the case and protects the fix. It must fail before the fix, otherwise it proves nothing.
Refactoring is a separate step. Move, rename, simplify, but do not change behaviour. Tests must stay green. If a test breaks, either the refactoring changed behaviour or the test checks an implementation detail.
Finally, do not confuse TDD with coverage. Writing tests afterwards can be useful but does not produce the same design benefits. TDD reveals dependencies and interfaces before they freeze. Use it where risk and uncertainty are high.
7. Coverage, mutation and static analysis
Line coverage shows code executed by tests, not code correctly verified. A line can be executed without any assertion checking its result. One hundred percent coverage can hide bugs; sixty percent can be enough for simple code.
Branch coverage checks both sides of conditions. Mutation coverage modifies the code (for example > to >=) and checks that tests fail. A low mutation score reveals tests that execute without verifying. These metrics are indicators, not absolute goals.
$ vendor/bin/phpunit --coverage-text
$ vendor/bin/infection --min-msi=70
$ vendor/bin/phpstan analyse --memory-limit=1G
$ vendor/bin/rector --dry-run
Static analysis finds errors without executing code: types, impossible calls, unused variables. It complements tests. A test can pass with an incorrect type at runtime; PHPStan reports it at analysis time. Configure a high level and address the errors.
Linters and formatters standardise style. They do not prove correctness but reduce review noise. A pipeline that fails on lint is fast and cheap. A pipeline that runs tests before lint wastes time.
Finally, do not chase a single number. A team can have 80% coverage and fragile tests, or 60% and solid tests on critical paths. Measure covered risk, stability and diagnosis time, not only the percentage.
8. Continuous integration and quality gates
Continuous integration runs checks automatically on every change. A typical pipeline: install dependencies, lint, static analysis, unit tests, integration tests, build. Order goes from fastest to slowest so failures happen early.
name: quality
on: [push, pull_request]
jobs:
tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
- run: composer install --no-interaction --prefer-dist
- run: vendor/bin/phpstan analyse --memory-limit=1G
- run: vendor/bin/phpunit
- run: php bin/console lint:twig templates
- run: php bin/console lint:yaml config translations content
A quality gate blocks merging if a test, lint or analysis fails. Without a gate, the pipeline becomes informational and errors accumulate. The gate must stay fast and reliable; a slow pipeline gets bypassed.
Cache dependencies and artefacts where possible. Isolate tests that need a database or service. Use a version matrix if the project supports several PHP versions. Failures must be reproducible locally.
A pipeline must also verify migrations and schema. A migration that passes locally but fails on an empty database blocks deployment. Add a step that applies migrations to a fresh database, then runs integration tests.
Finally, treat failures as signals, not noise. A red test must be fixed or removed with justification. A pipeline that is regularly red is no longer a gate; it becomes an ignored ritual. Trust in CI is an asset.
9. Test data, isolation and parallelisation
Test data must be explicit, minimal and deterministic. A factory creates a valid object with defaults, then each test overrides what matters. Avoid huge shared datasets that make tests interdependent.
final class ProductFactory
{
public static function createOne(array $overrides = []): Product
{
$data = array_merge([
'name' => 'Notebook',
'price' => Money::fromCents(350),
], $overrides);
return new Product($data['name'], $data['price']);
}
}
A test database can be reset by transaction, truncate or recreation. Each strategy has a cost. Transactions are fast but do not test commits; recreation is slow but more faithful. Choose according to the test type.
Parallelisation speeds up long suites but requires databases and files isolated per worker. A database shared between workers produces intermittent failures. Each worker needs its own schema or database, and tests must not depend on a global identifier.
Never copy production data into tests without anonymisation. A test containing personal data creates a GDPR risk and couples to the randomness of the real dataset. Use fictional data and reproducible generators.
Finally, clean side effects: temporary files, sent emails, queued messages, external calls. A test that leaves a file or message behind can affect the next one. Cleanup is part of the test, not an option.
10. Synthesis: a proportionate test strategy
A test strategy starts with risks: which features can harm the user, the business or security? Which parts change often? Which parts are hard to repair? The answers determine where to invest.
The cart's common thread combines levels: unit tests for Money, discounts and quantities; integration tests for the repository and migrations; functional tests for the order journey; an E2E test for payment. Each level covers what the other cannot see.
High risk : payment, authorisation, financial calculation → many tests
Medium risk : catalogue, search, forms → targeted tests
Low risk : static text, layout → few or no tests
Useful metrics are suite time, flaky failure rate, diagnosis time, critical-path coverage and the number of bugs escaped to production. A dashboard tracking only coverage misses the point.
Test debt exists: slow, fragile, redundant or assertion-free tests. Refactor tests like code. Remove a test that no longer protects anything, merge duplicates and stabilise journeys. A test suite is a maintained product.
Finally, quality is not perfection. It is a set of signals reliable enough to decide to ship. Tests, static analysis, review, monitoring and user feedback complement each other. None is enough alone; together they make changes reversible and production safer.
Exercise 1 — Choose the test level
For each case, choose unit, integration, functional or E2E: calculating a discount, a SQL search query, submitting a form, a real payment. Justify.
Solution
The discount is a pure rule: unit test. The SQL query depends on the database: integration test. Form submission goes through the framework: functional test. Real payment depends on a browser and an external service: E2E in a test environment. The lowest level that covers the risk is preferable.
Exercise 2 — Write a unit test
Write a PHPUnit test for Money::multiply() with 3 × 350 cents, then a test for a negative quantity. Which assertions do you use?
Solution
The first test uses assertSame(1050, $money->multiply(3)->cents). The second uses expectException(InvalidArgumentException::class) before the call. Tests cover the nominal case and the error. They do not test the private method or implementation details.
Exercise 3 — Replace the clock
An expiration policy depends on today's date. How do you make it testable without waiting 30 days? Write the test with a fixed clock.
Solution
Inject a Clock interface and use FixedClock in the test. The test creates a reference date and a creation date 31 days earlier, then checks isExpired(). Production uses a system clock. The test is deterministic and fast.
Exercise 4 — Repository integration test
Write a test that persists a cart, clears the EntityManager and reads it back. What precautions isolate the database?
Solution
The test uses a dedicated test database, reset before the suite, applies migrations, persists, flush, clear, then reads by identifier. It checks line count and total. The database must never be production, and data must be cleaned between tests.
Exercise 5 — Stabilise an E2E test
A browser test fails once in five after a click. Name three likely causes and three fixes.
Solution
Causes: too-short arbitrary wait, ambiguous or changed selector, data shared between tests. Fixes: wait for an observable condition, use a stable data-testid selector, isolate data per test. Also check animations and test order. A flaky test must be fixed, not ignored.
Exercise 6 — Quality pipeline
Propose a CI pipeline for a PHP 8.4 project with PHPUnit, PHPStan and lints. In what order should steps run and why?
Solution
Install dependencies, then YAML/Twig lint, static analysis, unit tests, integration tests, build. Fast steps run first to fail early. A gate blocks merging if any step fails. Dependencies are cached and migrations are tested on an empty database.
Capstone — cart quality
Deliver a test suite for the cart: unit tests for Money, discounts and quantities; a repository integration test; a functional test of the add journey; a documented E2E scenario. Add a CI pipeline, a justified coverage threshold and a note on covered and uncovered risks.
Grading: nominal, boundary and error cases; deterministic tests; doubles at boundaries; isolated database; functional journey; reproducible CI; interpreted metrics; documented limits.
Common mistakes and diagnostic method
Classic mistakes: testing implementation rather than behaviour, mocking the subject under test, using sleep in a test, sharing a database between tests, copying production data, ignoring a flaky test, chasing 100% coverage without risk, and forgetting error cases.
Method: reproduce the failure alone, check prepared data, read the assertion and stack, isolate the dependency, then fix the cause. If the test is hard to write, the dependency is probably misplaced. Add a regression case and run the full suite.
Self-assessment
You must be able to choose a test level, write a readable unit test, use a double, isolate a database, stabilise a journey, explain the TDD cycle, interpret coverage and mutation, and configure a quality gate.
Self-assessment: I can explain why a flaky test is dangerous; I can test an exception; I can replace time with a fixed clock; I can justify coverage by risk. To go further, study property-based testing, chaos engineering and production observability.
References
- PHPUnit 13 — Documentation, accessed 23 October 2026.
- Symfony — Testing, accessed 23 October 2026.
- Martin Fowler — Mocks Aren’t Stubs, accessed 23 October 2026.
- Infection — Mutation testing, accessed 23 October 2026.
- GitHub Actions — Documentation, accessed 23 October 2026.