Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 30 ยท Quality and Security

Testing Modules

Test PrestaShop modules with PHPUnit: keep logic out of core classes, wrap Configuration and Context behind interfaces, run integration tests in Docker, and use static analysis. Includes a runnable mini test harness.

A module that changes prices, sends emails or creates orders should have tests, because the store owner finds the bug in production, on a busy day, and it costs money. Testing PrestaShop code has a reputation for being hard. The reason is that much of PrestaShop's classic API is built from static calls (Configuration::get(), Db::getInstance(), Context::getContext()) and objects that load themselves from the database. A class that uses those directly can only be tested by booting the whole shop.

The way out is a design habit: put your business logic in plain classes that receive what they need through the constructor, and keep the thin PrestaShop-facing code (hooks, controllers) as small as possible. Then the logic can be tested in milliseconds without PrestaShop at all, and a few integration tests cover the glue. This lesson shows that structure, the PHPUnit setup, how to run integration tests in Docker, and the static-analysis tools you can add. The runnable examples use a small hand-built test harness so you can see how a test runner works. For the same ideas in another platform, compare Testing Magento Code.

What to test, and where

Layer What it proves Needs the shop?
Unit tests One class behaves correctly with fake collaborators No
Integration tests Your module installs, hooks run, SQL works against a real database Yes
Browser tests The checkout or product page works for a user Yes, and a browser
Static analysis Type errors, undefined methods, dead code, style No (but helped by the core code)
flowchart TB
    H["Hook / controller<br/>(thin, hard to test)"] --> L["Logic classes<br/>(plain PHP, unit tested)"]
    L --> A["Adapters / interfaces<br/>Config, Clock, Repository"]
    A --> P["PrestaShop APIs<br/>Configuration, Db, Context"]

Keep the thick part in the middle: logic that only talks to interfaces.

Structure the module for testing

A testable module keeps its classes under src/, loaded by Composer's autoloader, and its tests under tests/:

TEXT
deliverynotice/
  deliverynotice.php          (thin: hooks call src/ classes)
  composer.json
  phpunit.xml.dist
  src/
    Estimator/DeliveryEstimator.php
    Config/ConfigReader.php
  tests/
    Unit/DeliveryEstimatorTest.php

The composer.json declares PHPUnit as a development dependency and maps namespaces to folders, so tests can load your classes:

JSON
{
    "name": "acme/deliverynotice",
    "type": "prestashop-module",
    "autoload": {
        "psr-4": { "Acme\\Deliverynotice\\": "src/" }
    },
    "autoload-dev": {
        "psr-4": { "Acme\\Deliverynotice\\Tests\\": "tests/" }
    },
    "require-dev": {
        "phpunit/phpunit": "^10 || ^11"
    }
}

Choose the PHPUnit version that matches your PHP version; PrestaShop 8 and 9 support different PHP ranges, and the core project pins its own PHPUnit, so check the versions used by the shop you target. Remember to run composer install --no-dev for the release zip, so test tools are not shipped to merchants. See Anatomy of a Module for how the autoloader is loaded from the main class.

A minimal phpunit.xml.dist:

XML
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true" failOnWarning="true">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
    </testsuites>
</phpunit>

Run it with vendor/bin/phpunit. Settings and attributes differ slightly between PHPUnit versions, so follow the documentation of the version you install.

Wrap the static APIs behind interfaces

You cannot easily replace Configuration::get('X') inside a class under test. Wrap it once:

PHP
namespace Acme\Deliverynotice\Config;

interface ConfigReader
{
    public function getString(string $key, string $default = ''): string;
}

final class PrestaShopConfigReader implements ConfigReader
{
    public function getString(string $key, string $default = ''): string
    {
        $value = \Configuration::get($key);

        return $value === false ? $default : (string) $value;
    }
}

The logic receives a ConfigReader. In production you pass PrestaShopConfigReader; in a test you pass a double. Do the same for the clock (do not call new DateTime() or time() inside logic), for database access (a repository interface) and for anything that talks to the outside world (an HTTP client, a mailer). PrestaShop also provides adapter classes and a configuration interface for Symfony services, but a small interface of your own that only has the methods you use is easier to fake.

With PHPUnit, a double is created with createMock(ConfigReader::class) and configured with method('getString')->willReturn(...). For a tiny interface a hand-written fake class is often clearer than a mock, and it also works in the harness below. A real test looks like this (read-only):

PHP
use Acme\Deliverynotice\Config\ConfigReader;
use Acme\Deliverynotice\Estimator\DeliveryEstimator;
use PHPUnit\Framework\TestCase;

final class DeliveryEstimatorTest extends TestCase
{
    public function testOrderAfterCutoffShipsNextDay(): void
    {
        $config = $this->createMock(ConfigReader::class);
        $config->method('getString')->willReturnMap([
            ['DELIVERYNOTICE_CUTOFF', '14:00', '14:00'],
        ]);

        $estimator = new DeliveryEstimator($config);
        $result = $estimator->shipDate(new \DateTimeImmutable('2026-03-02 15:30'));

        self::assertSame('2026-03-03', $result->format('Y-m-d'));
    }
}

Mocks that check how often something is called (expects($this->once())) are useful when the call is the feature, for example "the mailer is called once". For most logic, assert on the returned value; tests that mirror the implementation line by line break whenever you refactor.

A mini test harness

PHPUnit does a few simple things: find the methods whose names start with test, call setUp() before each, catch assertion failures, and print a summary. The stand-in harness below does just that, and adds assertThrows and data sets. It is not PHPUnit and lacks most of its features, but running it shows what the real runner does for you. The class under test, StockAlert, decides whether to send a low-stock mail; its config reader, clock and mailer are hand-written fakes.

PHP A mini harness with fakes and a spy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the second test. It pins down the boundary (stock equal to the threshold), which is the spot where bugs hide. The mailer spy records calls so the test can check the side effect without sending anything.

Integration tests in Docker

Unit tests cannot tell you whether install() registers the hook, whether your SQL works on MySQL or whether the page renders. For that you need a real shop. The usual approach is a Docker setup with PrestaShop and MySQL containers, a test database separate from your development shop, and your module mounted into modules/. You then run PHPUnit inside the container, so that PHP, extensions and the shop's autoloader are the same as production:

Terminal
docker compose exec prestashop bash -lc \
  "cd modules/deliverynotice && composer install && vendor/bin/phpunit -c phpunit.integration.xml"

The integration bootstrap includes the shop's config/config.inc.php so that Configuration, Db and Module work. Typical integration checks are: the module installs and uninstalls cleanly (twice, to prove the uninstall removes what install added), the tables exist, the configuration keys are created and removed, the hook returns the expected HTML for a known product, and an upgrade script migrates old data. Reset the database to a known state before each test, using a transaction you roll back or a fresh dump, so that tests do not depend on order. Your own CI pipeline can run the same container commands, as in CI Pipelines in the Docker track.

The exact commands, container names and bootstrap files depend on the Docker image and the shop version you choose, so treat the snippet above as a pattern and check your own docker-compose.yml.

Static analysis and the Validator

Tests find wrong behavior; static analysis finds wrong code without running it.

  • PHPStan finds undefined methods, wrong types and unreachable code. Point it at your src/ folder and at the shop's core code so that it knows classes such as Module and Configuration. Start at a low strictness level and raise it over time.
  • PHP CS Fixer keeps the code style consistent. PrestaShop publishes a coding-standards configuration for modules that you can reuse.
  • The PrestaShop Validator is an online tool that checks a module zip against the rules of the Addons marketplace: files and folders (every folder needs an index.php), the license header, deprecated calls and the structure of config.xml. Run it before you submit a module for sale, and fix the warnings, because they often point to real compatibility problems.

A good minimum for a team: unit tests, PHPStan and the code-style check on every pull request, and the integration suite before a release.

When a bug report arrives, write the failing test first, at the lowest level that can show it. The test is a permanent guard, and it proves your fix works.

Test the boundaries

Most real bugs are at the edges: exactly at the threshold, at midnight, on the last day of the month, with an empty cart, with a missing configuration value, with an unknown currency. When you design a test list for a piece of logic, write down the normal case, each boundary on both sides, and each documented error. The second runnable example shows how a missing boundary test lets a bug through. A shipping-cutoff rule is implemented twice, once with < and once with <=, and the same suite is run against both.

PHP A boundary test catches an off-by-one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The buggy version passes four of the five cases. Without the "exactly at cutoff" case, it would look fine until a customer ordered at 14:00 and was told the parcel leaves tomorrow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a class that calls Configuration::get() directly hard to unit test?

    A hidden static dependency cannot be swapped for a fake. Wrapping it behind an interface passed to the constructor solves this.
  2. 2. Where does the business logic of a testable module belong?

    Hooks stay thin and call logic classes. Those classes can be unit tested without booting PrestaShop.
  3. 3. What do integration tests prove that unit tests cannot?

    Integration tests use the real framework and database, so wiring and SQL problems show up there.
  4. 4. Which tool checks a module package against the rules of the PrestaShop Addons marketplace?

    The Validator inspects the zip for structure, license headers, deprecated code and other marketplace requirements. CS Fixer only checks style.
  5. 5. A rule says orders up to and including 14:00 ship today. Which test case is the most valuable to add?

    Boundaries are where off-by-one bugs live. The exact cutoff minute distinguishes < from <=.

Summary

  • Put business logic in plain classes under src/ that receive collaborators through the constructor; keep hooks and controllers thin.
  • Wrap static APIs (Configuration, Db, Context) and time behind small interfaces so tests can pass fakes.
  • Configure PHPUnit with a phpunit.xml.dist, a Composer autoloader and require-dev; ship releases without dev dependencies.
  • Use Docker for integration tests of install, uninstall, SQL and hooks against a real database.
  • Add PHPStan, a code-style check and the PrestaShop Validator to catch problems without running code.
  • Test boundaries on both sides, and write a failing test for every bug before fixing it.

Next: Project: Delivery Estimate Module