Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 42 ยท Quality and Production

Testing Magento Code

A practical map of Magento 2.4 testing: PHPUnit unit tests, integration tests with fixtures, API-functional tests and MFTF, plus a runnable mini test runner with mocks.

Code that touches orders, prices and customers deserves tests, because a bug in a checkout plugin costs real money and the change that breaks it may be three modules away. Magento ships with a test setup built from several layers, each answering a different question: does this class do the right thing alone, does it work with a real database and the real framework, does the HTTP API behave, and does the storefront work in a browser?

This lesson gives you the map of those layers, the shape of a good unit test with mocks, and practice writing tests in plain PHP. Real Magento tests need a full installation and PHPUnit, so they are read-only here. The runnable examples use a tiny test runner, which also shows what PHPUnit does behind the scenes. For basic PHP object skills, see Abstract Classes and Interfaces.

The four layers

Layer Where it lives What it checks Speed
Unit dev/tests/unit and app/code/Vendor/Module/Test/Unit One class in isolation, with doubles for every dependency Milliseconds, no database
Integration dev/tests/integration and Test/Integration in a module Code working with the real framework and a test database Seconds, needs setup
API functional dev/tests/api-functional REST and SOAP endpoints over HTTP Slow, needs a running store
MFTF Test XML in Test/Mftf Browser flows like adding to cart and checking out Slowest

A healthy suite has many unit tests, a moderate number of integration tests for database and wiring problems, and a handful of browser tests for the main journeys. That pyramid shape keeps feedback fast.

flowchart TB
    A["MFTF<br/>browser journeys (few)"] --> B["API-functional<br/>endpoints (some)"]
    B --> C["Integration<br/>real framework and DB (more)"]
    C --> D["Unit<br/>one class at a time (most)"]

Prefer lower layers: they are faster and point to the problem more exactly.

Unit tests with PHPUnit

Magento uses PHPUnit. A unit test class lives under a Test/Unit folder that mirrors the class under test, and extends PHPUnit\Framework\TestCase. The code under test receives its collaborators through the constructor, which is exactly why Magento code uses constructor injection: you can hand the class doubles in a test.

This is a real-Magento-style test, read-only here:

PHP
<?php
declare(strict_types=1);

namespace Acme\Discount\Test\Unit\Model;

use Acme\Discount\Model\Calculator;
use Magento\Framework\App\Config\ScopeConfigInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

class CalculatorTest extends TestCase
{
    private ScopeConfigInterface|MockObject $scopeConfig;
    private Calculator $calculator;

    protected function setUp(): void
    {
        $this->scopeConfig = $this->createMock(ScopeConfigInterface::class);
        $this->calculator = new Calculator($this->scopeConfig);
    }

    public function testNoDiscountWhenDisabled(): void
    {
        $this->scopeConfig->method('isSetFlag')->willReturn(false);

        self::assertSame(1000, $this->calculator->apply(1000));
    }

    /**
     * @dataProvider percentProvider
     */
    public function testAppliesConfiguredPercent(int $percent, int $price, int $expected): void
    {
        $this->scopeConfig->method('isSetFlag')->willReturn(true);
        $this->scopeConfig->method('getValue')->willReturn((string) $percent);

        self::assertSame($expected, $this->calculator->apply($price));
    }

    public static function percentProvider(): array
    {
        return [
            '10 percent' => [10, 1000, 900],
            '50 percent' => [50, 999, 500],
        ];
    }
}

Run it from the Magento root with a PHPUnit configuration, for example vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Acme/Discount/Test/Unit. The exact configuration path and the PHPUnit version depend on your Magento release, so follow the files in your own project (newer PHPUnit versions favour PHP attributes over the @dataProvider annotation).

Good unit tests follow a few habits:

  • Arrange, act, assert. Build the object and its doubles, call one method, check the result.
  • One reason to fail per test. Name tests after behaviour: testNoDiscountWhenDisabled.
  • Fake only your boundaries. Replace config, repositories, loggers and the clock. Do not mock the class you are testing.
  • Use createMock and getMockBuilder for interfaces. For classes with complicated constructors, Magento also offers an object manager helper for tests that builds objects with mock arguments.
  • Avoid the real ObjectManager in unit tests. If the code under test calls it directly, that is a design problem to fix, as explained in The Object Manager and Constructor Injection.

A mini test runner

Here is the same idea in plain PHP. The runner finds methods that start with test, runs each, and reports passes and failures. The stand-in config reader is a hand-written double, and the discount calculator is the class under test.

PHP Unit tests with a hand-written double

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 last test fails on purpose, so you see what a failure message looks like. In PHPUnit the output is richer (a diff, a stack trace, the line number) but the principle is the same: an assertion compares an expected value with an actual one.

The data provider in the PHPUnit example runs one test method over several rows. A plain loop does the same in the stand-in below, where we also build a spy, a double that records calls so a test can check how a collaborator was used. PHPUnit's expects($this->once())->method('log')->with(...) does this for you.

PHP Spies, call checks and data sets

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.

A spy keeps a test honest about behaviour, but do not overuse it: asserting on every internal call makes tests break whenever you refactor. Check results first, and interactions only when the call itself is the feature, such as "an email is sent once".

Integration tests

Unit tests cannot tell you whether your db_schema.xml is valid, your di.xml wires correctly, or your collection query returns the right rows. Integration tests boot a real Magento instance against a separate test database, configured in dev/tests/integration/etc/install-config-mysql.php, and run in a mode where each test is wrapped so changes do not leak. The test class extends PHPUnit\Framework\TestCase and uses Magento\TestFramework\Helper\Bootstrap::getObjectManager() to obtain real objects. Annotations control the environment:

PHP
/**
 * @magentoDataFixture Acme_Discount::Test/Integration/_files/products.php
 * @magentoDbIsolation enabled
 * @magentoAppArea frontend
 * @magentoConfigFixture default_store acme_discount/general/enabled 1
 */
public function testPriceIsDiscounted(): void
{
    $calculator = Bootstrap::getObjectManager()->create(Calculator::class);
    // ... assert against real data created by the fixture
}

Data fixtures are PHP scripts that create the records a test needs, with an optional _rollback.php to remove them. Setting up the integration environment is more work than for unit tests, so read the official testing documentation for the version you run. Use integration tests for the risky glue: schema, plugins that must fire, repositories and collections, and anything depending on configuration scopes.

API-functional tests and MFTF at a glance

API-functional tests call your REST or GraphQL endpoint over HTTP against an installed store and check the response, often by extending Magento\TestFramework\TestCase\WebapiAbstract. They prove that the route, the ACL and the data shape work together, which is valuable for the endpoints you build in The REST API.

MFTF, the Magento Functional Testing Framework, drives a real browser using test files written in XML (actions, sections, pages, data) and run through Codeception. It is the tool for end-to-end journeys such as "a guest buys a simple product". It needs a configured browser driver and is slow and sensitive to theme markup, so keep these tests few and focused on money paths.

When a bug is reported, write the failing test first, at the lowest layer that can show it. A bug that a one-class unit test can reproduce should not need a browser run.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which test layer needs a real database and the real Magento framework?

    Integration tests boot Magento against a separate test database, so schema, DI wiring and queries are tested for real. Unit tests use doubles instead.
  2. 2. Why does constructor injection make unit testing easier?

    When dependencies come in through the constructor, a test can supply a mock or hand-written double, so the class runs in isolation.
  3. 3. What should a unit test do with the class under test?

    Mocking the class under test proves nothing. Fake the collaborators at the boundaries and exercise the real class.
  4. 4. What is MFTF best used for?

    MFTF drives a browser from XML test files. It is slow and brittle, so reserve it for critical flows like checkout.
  5. 5. A bug can be reproduced by calling one class with certain inputs. Where should its regression test live?

    Write the test at the lowest layer that can show the bug. A unit test is fastest and points directly at the cause.

Summary

  • Magento tests form a pyramid: many unit tests, some integration and API-functional tests, few MFTF browser tests.
  • Unit tests run one class with doubles; constructor injection is what makes that easy.
  • Integration tests use the real framework and a test database with fixtures and annotations such as @magentoDataFixture and @magentoDbIsolation.
  • Check results first, assert on interactions only when the call is the feature, and never mock the class under test.
  • Reproduce every bug with a failing test at the lowest possible layer, then fix it.

Next: Performance and Security