Skip to content

Add convenient test assertions for web APIs#2887

Merged
dunglas merged 2 commits into
api-platform:masterfrom
dunglas:testing-assert
Jun 28, 2019
Merged

Add convenient test assertions for web APIs#2887
dunglas merged 2 commits into
api-platform:masterfrom
dunglas:testing-assert

Conversation

@dunglas

@dunglas dunglas commented Jun 27, 2019

Copy link
Copy Markdown
Member
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.

Comment thread src/Bridge/Symfony/Bundle/Test/ApiTestAssertionsTrait.php
Comment thread src/Bridge/Symfony/Bundle/Test/BrowserKitAssertionsTrait.php
@dunglas
dunglas merged commit efa341c into api-platform:master Jun 28, 2019
@dunglas
dunglas deleted the testing-assert branch June 28, 2019 08:06
Comment thread composer.json
Comment thread src/Bridge/Symfony/Bundle/Test/ApiTestAssertionsTrait.php
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