Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 30 ยท Quality and Production

Testing Plugins

Test Shopware 6 plugins with PHPUnit unit and integration tests, test traits, database transactions, mocks and Jest for the admin, plus runnable test helpers.

A plugin runs inside someone else's shop, next to dozens of other extensions, on data you have never seen. You cannot click through every case by hand before each release. Automated tests give you a fast answer to the question "did my last change break anything?", and they are what lets you upgrade to a new Shopware version without fear.

This lesson explains the testing layers that fit Shopware plugins: unit tests for plain classes, integration tests that boot the kernel and use the database, and Jest tests for the admin's Vue code. The real test setup is read-only here, because Shopware cannot run on this site. The runnable examples are PHP stand-ins: a tiny assertion toolkit, a service built for testability, and a database transaction that is rolled back after a test. If you already know the general ideas from Testing in Symfony, most of this will feel familiar.

Which kind of test to write

Not every test needs Shopware. Choose the lightest test that proves the behavior.

Kind Boots the kernel? Uses the database? Good for
Unit test No No Pure logic: price rounding, mapping, validation rules, string building
Integration test Yes Yes Services wired from services.xml, repositories, subscribers, migrations
End-to-end test Yes, plus a browser Yes A few critical flows, such as checkout with your payment method
flowchart TB
    E2E["End-to-end<br/>few, slow"] --> INT["Integration tests<br/>kernel + database"]
    INT --> UNIT["Unit tests<br/>many, fast"]

Write many fast unit tests, a moderate number of integration tests and very few end-to-end tests.

A useful habit is to keep logic in classes that take their dependencies through the constructor. Such classes are unit-testable with fakes, and you reserve integration tests for the glue, such as "is the service registered, is the subscriber subscribed, does the query return the right rows".

Setting up PHPUnit in a plugin

A plugin has its own phpunit.xml.dist and a tests folder. The bootstrap file starts Shopware's test environment by pointing it at your project (read-only):

PHP
<?php declare(strict_types=1);

use Shopware\Core\TestBootstrapper;

$loader = (new TestBootstrapper())
    ->setProjectDir($_SERVER['PROJECT_ROOT'] ?? dirname(__DIR__, 4))
    ->setLoadEnvFile(true)
    ->setForceInstall(false)
    ->bootstrap()
    ->getClassLoader();

$loader->addPsr4('Swag\\Badge\\Tests\\', __DIR__);
XML
<phpunit bootstrap="tests/TestBootstrap.php" colors="true">
    <testsuites>
        <testsuite name="SwagBadge">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <php>
        <env name="APP_ENV" value="test"/>
    </php>
</phpunit>

The bootstrapper's method names and the project directory layout have changed over Shopware's history, so compare with the plugin skeleton your version generates before copying. Run the suite from the project root with vendor/bin/phpunit --configuration custom/plugins/SwagBadge/phpunit.xml.dist. Tests use a test database, usually the project database name with a _test suffix, so they never touch real shop data.

Unit tests

A unit test needs no framework, only PHPUnit and plain objects. Imagine a service that decides which badge text to show for a product (read-only):

PHP
final class BadgeLabelResolverTest extends TestCase
{
    public function testNewProductsGetTheNewLabel(): void
    {
        $now = new \DateTimeImmutable('2030-06-15');
        $resolver = new BadgeLabelResolver(fn() => $now);

        $label = $resolver->resolve(releaseDate: new \DateTimeImmutable('2030-06-01'), stock: 10);

        static::assertSame('New', $label);
    }

    public function testSoldOutBeatsNew(): void
    {
        $resolver = new BadgeLabelResolver(fn() => new \DateTimeImmutable('2030-06-15'));

        static::assertSame('Sold out', $resolver->resolve(new \DateTimeImmutable('2030-06-14'), 0));
    }
}

The clock is a constructor argument, so the test fixes time. Never call new \DateTimeImmutable() or time() deep inside business logic if you want a deterministic test. The same goes for random values and external HTTP calls. Pass them in, and pass fakes in tests.

Integration tests and the Shopware traits

When you need the container, the DAL or the database, you use Shopware's test traits. The most useful one is IntegrationTestBehaviour, which combines several smaller traits (read-only):

PHP
use PHPUnit\Framework\TestCase;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour;
use Shopware\Core\Framework\Uuid\Uuid;

final class BadgeRepositoryTest extends TestCase
{
    use IntegrationTestBehaviour;

    public function testBadgeCanBeCreatedAndRead(): void
    {
        /** @var EntityRepository $repository */
        $repository = static::getContainer()->get('swag_badge.repository');
        $context = Context::createDefaultContext();
        $id = Uuid::randomHex();

        $repository->create([['id' => $id, 'name' => 'Sale', 'color' => '#ff3d58']], $context);

        $badge = $repository->search(new Criteria([$id]), $context)->first();

        static::assertNotNull($badge);
        static::assertSame('Sale', $badge->get('name'));
    }
}

The combined trait gives you the kernel and container, a database transaction that is rolled back after each test, and helpers for caches and time. The rollback is why integration tests can create products freely without leaving a mess, and why two tests never see each other's data. The location of the trait and a few helpers have moved between major versions, and newer versions favor PHP attributes and dedicated base classes, so check your version's own tests in the core repository for the current style.

Two cautions apply to integration tests:

  • DDL statements break transactions. In MySQL, CREATE TABLE and ALTER TABLE end the open transaction, so the rollback no longer cleans up. Test migrations in their own dedicated way, not with the rollback trick.
  • They are slower. Booting the kernel takes time. Do not use integration tests for pure logic you could check with a unit test.

Services should be fetched from the container only inside tests. In production code, inject them (see Services and the Dependency Injection Container). A service that is private in the container may not be fetchable in tests unless your version marks test services public. A pragmatic alternative is to construct your service by hand with real or fake dependencies.

Mocking and fakes

PHPUnit can create test doubles with createMock(), which is handy when a dependency has a big interface you only call once. For repositories, a hand-written in-memory fake is often clearer: it implements the same small interface your code depends on and keeps data in an array. Fakes read like the real thing in assertions and do not break when you rename a method that a mock expected.

A rule that avoids many headaches: do not mock what you do not own deeply. Mocking EntityRepository call by call ties the test to how your code talks to the DAL instead of what it achieves. Test the query logic once against the real database, and test everything above it with a fake behind your own interface.

Testing the admin with Jest

Admin code is JavaScript, so it is tested with Jest and Vue Test Utils. The core provides a Jest preset for admin tests. A plugin's jest.config.js extends it, and the test file mounts the component (read-only):

JavaScript
import { mount } from '@vue/test-utils';

async function createWrapper(propsData = {}) {
    return mount(await wrapTestComponent('swag-badge-label', { sync: true }), {
        props: { text: 'Limited edition 2030', ...propsData },
    });
}

describe('swag-badge-label', () => {
    it('shortens long text', async () => {
        const wrapper = await createWrapper();
        expect(wrapper.text()).toBe('Limited edit');
    });
});

wrapTestComponent and the global setup come from the core's preset and differ between versions. Check your version's admin tests for the exact helpers. The principle stays the same: mount one component, give it props, assert on rendered text and emitted events. Test your logic, not the framework.

Running tests in CI

Run the same commands on every push. A pipeline for a plugin needs a Shopware environment, because integration tests boot the kernel. A typical outline (read-only):

YAML
name: tests
on: [push, pull_request]
jobs:
  phpunit:
    runs-on: ubuntu-latest
    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_ROOT_PASSWORD: root
        ports: ["3306:3306"]
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with:
          php-version: "8.3"
      - run: composer create-project shopware/production /tmp/shop
      - run: |
          cd /tmp/shop
          composer config repositories.plugin path $GITHUB_WORKSPACE
          composer require swag/badge:@dev
          bin/console system:install --basic-setup --create-database
          vendor/bin/phpunit --configuration custom/plugins/SwagBadge/phpunit.xml.dist

Adapt versions and details to your project. Run the matrix against each Shopware and PHP version you claim to support, which leads directly into Packaging, Deployment and Updates.

A tiny test toolkit you can run here

The first stand-in builds the pieces PHPUnit gives you: assertions, a test runner that reports failures and a service whose clock and stock source are injected. It shows why dependency injection makes tests easy.

PHP Assertions, a runner and an injectable service

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 can see how a failure message reads. Good failure messages say what was expected and what happened, which is exactly what PHPUnit's assertSame does for you.

Transactions as test isolation

The second stand-in shows what the rollback behind IntegrationTestBehaviour achieves, using SQLite in memory. Each test starts a transaction, changes data and rolls back, so the next test starts clean. This is a simplified model of the idea, not Shopware's trait.

PHP Rolling back the database after each test

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.

Every test saw the seed row plus only its own inserts, and the table ends as it started. If a test ran CREATE TABLE in MySQL, the implicit commit would break this pattern, which is why migrations need their own tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which test is the best fit for checking a pure price-rounding function?

    Pure logic needs no framework. Unit tests are the fastest, so use them wherever the code allows.
  2. 2. What does the rollback in IntegrationTestBehaviour achieve?

    Wrapping each test in a transaction that is rolled back keeps tests independent of each other and of their order.
  3. 3. Why should a service receive the clock through its constructor?

    A hidden call to the current time makes results depend on when the test runs. Injecting it lets the test choose the time.
  4. 4. Why is it risky to test a migration with the rollback trick in MySQL?

    MySQL commits implicitly around DDL. Migrations therefore need dedicated tests that clean up on their own.

Summary

  • Pick the lightest test that proves the behavior: unit tests for logic, integration tests for wiring and the DAL, very few end-to-end tests.
  • A plugin has its own phpunit.xml.dist and bootstrap that starts Shopware's test environment against a test database.
  • IntegrationTestBehaviour provides the kernel, the container and a rolled-back transaction per test. The exact trait names and locations depend on your Shopware version.
  • Inject clocks, randomness and external services so tests can fix them, and prefer small in-memory fakes over deep mocks of the DAL.
  • Test admin components with Jest and Vue Test Utils through the core's preset.
  • Run tests in CI against every Shopware and PHP version you support.

Next: Security and Performance.