Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

API Integration Tests with ApiTestCase

API Integration Tests with ApiTestCase

~16 Min. Lesezeit Zuletzt aktualisiert am August 8, 2026

EXACTLY as the Symfony course (chapter 44) used WebTestCase for HTTP tests, API Platform ships a SPECIALIZED ApiTestCase base class that ADDS JSON-LD-specific assertions.

Checking the test package

docker compose exec php composer require --dev api-platform/test

Usually ALREADY part of the api-platform distribution – the command installs it AFTERWARD, if NOT PRESENT.

Writing the first test

api/tests/ProjectResourceTest.php
<?php

declare(strict_types=1);

namespace App\Tests;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;

final class ProjectResourceTest extends ApiTestCase
{
    public function testGetCollection(): void
    {
        $response = static::createClient()->request('GET', '/api/projects');

        self::assertResponseIsSuccessful();
        self::assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
        self::assertJsonContains(['@context' => '/api/contexts/Project']);
    }
}

assertJsonContains is the MOST IMPORTANT addition COMPARED to classic WebTestCase assertions – it checks THAT the named keys/values are PRESENT in the JSON, WITHOUT having to compare the ENTIRE response exactly.

Validating against the JSON schema

public function testGetCollectionMatchesSchema(): void
{
    static::createClient()->request('GET', '/api/projects');

    self::assertMatchesResourceCollectionJsonSchema(\App\Entity\Project::class);
}

assertMatchesResourceCollectionJsonSchema validates the response AGAINST the JSON schema AUTOMATICALLY derived from #[ApiResource] – if the structure LATER ACCIDENTALLY changes (e.g. a field FORGOTTEN to rename), THIS test FAILS IMMEDIATELY.

A writing test

public function testCreateProject(): void
{
    static::createClient()->request('POST', '/api/projects', [
        'json' => ['name' => 'Test project'],
        'headers' => ['Content-Type' => 'application/ld+json'],
    ]);

    self::assertResponseStatusCodeSame(201);
    self::assertJsonContains(['name' => 'Test project']);
}

Achtung: WITHOUT authentication (block 6), this test CURRENTLY FAILS with 401 – chapter 94 shows HOW test users and tokens get provided for tests, SO authenticated endpoints REMAIN TESTABLE.

Running the tests

docker compose exec php bin/phpunit

Tipp: ApiTestCase INHERITS from KernelTestCase (EXACTLY like WebTestCase in the Symfony course) – static::createClient() boots the ENTIRE application in an isolated test environment, with its OWN database connection (.env.test), which stays SEPARATE from the development database.