Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 62 ยท Caching, Performance and Testing

Testing with PHPUnit

Test Symfony apps with PHPUnit: unit tests, KernelTestCase for services, WebTestCase and the client for HTTP, assertions, test database, plus a runnable test stand-in.

Tests are what let you change code without fear. Symfony is built around PHPUnit and ships helpers on top of it for the three kinds of tests you will write: unit tests for plain classes, integration tests that boot the kernel and use real services, and functional (application) tests that send HTTP requests to your app and check the responses.

This lesson explains each kind, what the Symfony base classes add, how to deal with the database, and the assertions you will use daily. PHPUnit and the Symfony kernel cannot run on this site, so the real test code is read-only; the runnable parts are a mini test runner and a fake HTTP client in plain PHP that show how the pieces fit. It builds on services and the container and the request lifecycle.

Setting up

A Symfony project created with the webapp template already has what you need. If not, add the test pack and run tests through the bundled wrapper:

Terminal
# real Symfony, read-only
composer require --dev symfony/test-pack
php bin/phpunit
php bin/phpunit tests/Service/PriceCalculatorTest.php
php bin/phpunit --filter testApplyDiscount

Tests live in tests/, mirror the structure of src/, and class names end in Test. The phpunit.dist.xml file configures PHPUnit, and sets APP_ENV=test so Symfony reads config/packages/test/* and .env.test. See configuration and environments.

flowchart TB
    U["Unit test<br/>TestCase: one class, no kernel"] --> F1["Fast, many"]
    I["Integration test<br/>KernelTestCase: real services"] --> F2["Medium"]
    W["Functional test<br/>WebTestCase: requests and responses"] --> F3["Slowest, fewest"]

Prefer many fast unit tests, some integration tests and a few end-to-end functional tests.

Unit tests

If a class has no dependency on the framework, test it with plain PHPUnit. This is the best kind of test: fast and precise.

PHP
// tests/Service/PriceCalculatorTest.php (real PHPUnit, read-only)
namespace App\Tests\Service;

use App\Service\PriceCalculator;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

final class PriceCalculatorTest extends TestCase
{
    public function testAppliesPercentageDiscount(): void
    {
        $calculator = new PriceCalculator();

        $this->assertSame(9000, $calculator->discount(10000, 10));
    }

    #[DataProvider('invalidPercentages')]
    public function testRejectsInvalidPercentages(int $percent): void
    {
        $this->expectException(\InvalidArgumentException::class);

        (new PriceCalculator())->discount(10000, $percent);
    }

    public static function invalidPercentages(): iterable
    {
        yield 'negative' => [-1];
        yield 'over 100' => [101];
    }
}

Design for this: when services take their dependencies through the constructor (see autowiring), a unit test passes in a fake or a PHPUnit mock instead of the real collaborator, and no container is needed. PHPUnit 10 and later use attributes such as #[DataProvider] and #[Test], and data providers must be static.

Integration tests with KernelTestCase

Sometimes you want to test a service wired by the real container: the configuration, the autowiring and the real database. KernelTestCase boots the kernel for you:

PHP
// tests/Service/ReportServiceTest.php (real Symfony, read-only)
namespace App\Tests\Service;

use App\Service\ReportService;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

final class ReportServiceTest extends KernelTestCase
{
    public function testMonthlyTotals(): void
    {
        self::bootKernel();
        $container = static::getContainer();

        $service = $container->get(ReportService::class);

        $this->assertCount(12, $service->monthlyTotals(2025));
    }
}

getContainer() returns a special test container that can also fetch private services, which a normal container refuses to do. Services you want to test this way must exist in the container; autowired services that nothing uses may be removed during compilation, which is why the test container exposes them. You can replace a service for a test with $container->set(MailerInterface::class, $fake) before fetching the service that uses it, or use when@test configuration to alias a real service to a fake one.

Functional tests with WebTestCase

WebTestCase creates a client that runs a request through your whole application, without a network or web server. It is the right place to test routing, controllers, security and templates together.

PHP
// tests/Controller/BookControllerTest.php (real Symfony, read-only)
namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

final class BookControllerTest extends WebTestCase
{
    public function testListPage(): void
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/books');

        $this->assertResponseIsSuccessful();
        $this->assertSelectorTextContains('h1', 'Books');
        $this->assertCount(3, $crawler->filter('li.book'));
    }

    public function testCreateBookThroughApi(): void
    {
        $client = static::createClient();
        $client->jsonRequest('POST', '/api/books', ['title' => 'Dune']);

        $this->assertResponseStatusCodeSame(201);
        $this->assertResponseHeaderSame('content-type', 'application/json');
    }

    public function testFormSubmission(): void
    {
        $client = static::createClient();
        $client->request('GET', '/books/new');
        $client->submitForm('Save', ['book[title]' => 'Emma']);

        $this->assertResponseRedirects('/books');
        $client->followRedirect();
        $this->assertSelectorExists('.flash-success');
    }

    public function testAdminNeedsLogin(): void
    {
        $client = static::createClient();
        $client->request('GET', '/admin');

        $this->assertResponseRedirects('/login');
    }
}

The client keeps cookies between requests like a browser, so a login followed by another request stays logged in. To act as a given user without going through the login form, load a user and call $client->loginUser($user) (see authentication).

Useful assertions, all provided by the framework bundle's test traits:

  • Status: assertResponseIsSuccessful(), assertResponseStatusCodeSame(404), assertResponseRedirects('/path').
  • Headers and cookies: assertResponseHeaderSame(), assertResponseHasCookie().
  • HTML: assertSelectorExists(), assertSelectorTextContains(), assertPageTitleSame(); use the $crawler for deeper checks.
  • Forms: assertFormValue(), assertInputValueSame().
  • Services: assertEmailCount(1), assertQueuedEmailCount() and assertEmailSubjectContains() once you capture mail in tests (the test environment typically uses a null transport).

Before PHPUnit 10, tests extended PHPUnit\Framework\TestCase with annotations such as @dataProvider. Modern projects use attributes; older code you meet may still use annotations.

The test database

Never run tests against your development database. Symfony uses .env.test (and .env.test.local) when APP_ENV=test, so you point DATABASE_URL at a separate database there. Doctrine's bundle also appends a _test suffix to the database name in the test environment (configurable with the dbname_suffix option), and with ParaTest it can append a token for parallel runs.

The usual workflow:

Terminal
# real Symfony, read-only
php bin/console --env=test doctrine:database:create
php bin/console --env=test doctrine:migrations:migrate --no-interaction
php bin/phpunit

The harder problem is keeping tests independent. Two common solutions: wrap every test in a database transaction that is rolled back (the dama/doctrine-test-bundle package does this transparently), or create the data each test needs from factories (see fixtures and factories). Zenstruck Foundry offers both through a ResetDatabase trait. Tests that depend on the state left by other tests are the number one cause of flaky suites.

Test behaviour, not wiring. A good functional test says "an admin can publish a draft and the public page shows it", not "the container has a service called X". Tests that mirror the implementation break on every refactor without catching bugs.

A test runner you can run

PHPUnit itself is a library you install with Composer. To see what it does, here is a tiny runner in plain PHP: it finds methods starting with test, calls them, catches assertion failures and prints a report. This is a stand-in, not PHPUnit.

PHP A mini test runner (stand-in)

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 what a red result looks like: it says what was expected and what was received. Real PHPUnit prints the same information with a diff, a stack trace and a summary, and returns a non-zero exit code so a CI server can stop the build.

A fake client for functional tests

WebTestCase's client is, in essence, a function from a request to a response that runs your application in-process. The stand-in below replaces the application with a small router and checks status codes, redirects and body content the same way the real assertions do.

PHP A fake HTTP client and response assertions (stand-in)

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 shape is the same as a real functional test: arrange (create the client), act (make a request), assert (status, redirect target, content). Note that the third request builds on the state created by the second, as it would with a real database inside one test, which is fine within a test but must never leak between tests.

Practical advice

  • Run the suite in CI on every push, and keep it fast: slow suites get skipped.
  • Mock only what you own or what is slow (mail, HTTP APIs, clocks). Use Symfony's MockHttpClient for outgoing HTTP calls and MockClock for time.
  • Add a regression test for every bug you fix, before fixing it.
  • Keep functional tests few and focused on the main paths; push detailed rules down into unit tests.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which base class boots the kernel so you can fetch real services from the container?

    KernelTestCase boots the kernel and gives you the test container. WebTestCase builds on it and adds the HTTP client.
  2. 2. What does WebTestCase's client do?

    The client simulates a browser without a network or web server, and keeps cookies between requests.
  3. 3. Why should tests use a separate database?

    Tests create, change and delete data. The test environment points DATABASE_URL (or a _test suffix) at a separate database.
  4. 4. What is the main cause of flaky test suites mentioned in this lesson?

    Each test should create its own data or run inside a rolled-back transaction so the order of tests does not matter.

Summary

  • Run tests with php bin/phpunit; the test environment (APP_ENV=test) loads its own configuration.
  • Write plain TestCase unit tests for framework-free classes, KernelTestCase for services from the container, and WebTestCase with the client for whole-request tests.
  • The client keeps cookies, follows redirects, submits forms and has assertions for status, headers, selectors and forms.
  • Use a separate test database and keep tests independent (transactions or factories).
  • Prefer many unit tests, some integration tests and a few functional tests; mock slow or external collaborators.
  • The runnable examples are plain-PHP stand-ins; the PHPUnit and Symfony tests are real and read-only here.

Next up: Performance and Deployment.