Skip to content

Add convenient test assertions for web APIs #2887

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 28, 2019

Conversation

dunglas
Copy link
Member

@dunglas dunglas commented Jun 27, 2019

Q A
Bug fix? no
New feature? yes
BC breaks? no
Deprecations? no
Tests pass? yes
Fixed tickets n/a
License MIT
Doc PR api-platform/docs#875

This is a follow up PR to #2608. It introduces convenient PHPUnit assertions to test web APIs. A quick example is worth thousand words:

<?php

use use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;

class ClientTest extends ApiTestCase
{
    public function testMyApi(): void
    {
        self::createClient()->request('GET', '/secured_dummies', ['auth_basic' => ['dunglas', 'kevin']]);

        $this->assertResponseIsSuccessful();
        $this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
        // All web assertions provided by Symfony can also be used

        // Exact matching
        $this->assertJsonEquals([
            '@context' => '/contexts/SecuredDummy',
            '@id' => '/secured_dummies',
            '@type' => 'hydra:Collection',
            'hydra:member' => [],
            'hydra:totalItems' => 0,
        ]);

        // Partial matching
        $this->assertJsonContains(
            [
                '@context' => '/contexts/SecuredDummy',
                '@id' => '/secured_dummies',
            ]
        );

        // The JSON Schema can be represented as a string or a PHP array
        $this->assertMatchesJsonSchema(<<<JSON
{
  "type": "object",
  "properties": {
    "@context": {"pattern": "^/contexts/SecuredDummy$"},
    "@id": {"pattern": "^/secured_dummies$"},
    "@type": {"pattern": "^hydra:Collection"},
    "hydra:member": {}
  },
  "additionalProperties": true,
  "required": ["@context", "@id", "@type", "hydra:member"]
}
JSON
        );
    }
}

All HTTP assertions provided by Symfony can be used!

This PR also migrates our test suite to PHPUnit 8. Related to symfony/symfony#32207.

@dunglas dunglas merged commit efa341c into api-platform:master Jun 28, 2019
@dunglas dunglas deleted the testing-assert branch June 28, 2019 08:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants