Skip to content

Commit 639740c

Browse files
committed
docs: add testing doc for Laravel & cleanup
Introduce comprehensive testing documentation for Laravel, covering both Pest and PHPUnit frameworks. This includes detailed examples of writing functional tests, generating model factories, and running tests, along with information on continuous integration. Merge Symfony tests docs to be at the same place. Using core testing doc to introduce API Platform testing and redirecting to Laravel & Symfony testing documentations. docs: merge testing-utilities & testing docs for Symfony and up docs: restore core testing doc to introduces tests and redirections chore: relocated symfony testing doc
1 parent 31bc652 commit 639740c

File tree

6 files changed

+771
-247
lines changed

6 files changed

+771
-247
lines changed

core/getting-started.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ If you are starting a new project, the easiest way to get API Platform up is to
1313

1414
It comes with the API Platform core library integrated with [the Symfony framework](https://symfony.com), [the schema generator](../schema-generator/),
1515
[Doctrine ORM](https://www.doctrine-project.org),
16-
[NelmioCorsBundle](https://github.com/nelmio/NelmioCorsBundle) and [test assertions dedicated to APIs](testing.md).
16+
[NelmioCorsBundle](https://github.com/nelmio/NelmioCorsBundle) and [test assertions dedicated to APIs](../symfony/testing-utilities.md).
1717

1818
[MongoDB](mongodb.md) and [Elasticsearch](elasticsearch.md) can also be easily enabled.
1919

core/json-schema.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ docker compose exec php \
2525

2626
In a unit testing context, API Platform does not use the same schema version as the schema used when generating the API documentation. The version used by the documentation is the OpenAPI Schema version and the version used by unit testing is the JSON Schema version.
2727

28-
When [Testing the API](testing.md), JSON Schemas are useful to generate and automate unit testing. API Platform provides specific unit testing functionalities like [`assertMatchesResourceCollectionJsonSchema()`](testing.md#writing-functional-tests) or [`assertMatchesResourceItemJsonSchema()`](testing.md#writing-functional-tests) methods.
28+
When [Testing the API](../symfony/testing-utilities.md), JSON Schemas are useful to generate and automate unit testing. API Platform provides specific unit testing functionalities like [`assertMatchesResourceCollectionJsonSchema()`](../symfony/testing-utilities.md#writing-functional-tests) or [`assertMatchesResourceItemJsonSchema()`](../symfony/testing-utilities.md#writing-functional-tests) methods.
2929
These methods generate a JSON Schema then do unit testing based on the generated schema automatically.
3030

3131
Usually, the fact that API Platform uses a different schema version for unit testing is not a problem, but sometimes you may need to use the [`ApiProperty`](openapi.md#using-the-openapi-and-swagger-contexts) attribute to specify a [calculated field](serialization.md#calculated-field) type by overriding the OpenAPI Schema for the calculated field to be correctly documented.
3232

33-
When you will use [`assertMatchesResourceCollectionJsonSchema()`](testing.md#writing-functional-tests) or [`assertMatchesResourceItemJsonSchema()`](testing.md#writing-functional-tests) functions the unit test will fail on this [calculated field](serialization.md#calculated-field) as the unit testing process doesn't use the `openapi_context` you specified
33+
When you will use [`assertMatchesResourceCollectionJsonSchema()`](../symfony/testing-utilities.md#writing-functional-tests) or [`assertMatchesResourceItemJsonSchema()`](../symfony/testing-utilities.md#writing-functional-tests) functions the unit test will fail on this [calculated field](serialization.md#calculated-field) as the unit testing process doesn't use the `openapi_context` you specified
3434
because API Platform is using the JSON Schema version instead at this moment.
3535

3636
So there is a way to override JSON Schema specification for a specific property in the JSON Schema used by the unit testing process.
@@ -84,4 +84,4 @@ To generate JSON Schemas programmatically, use the `api_platform.json_schema.sch
8484
## Testing
8585

8686
API Platform provides a PHPUnit assertion to test if a response is valid according to a given Schema: `assertMatchesJsonSchema()`.
87-
Refer to [the testing documentation](testing.md) for more details.
87+
Refer to [the testing documentation](../symfony/testing-utilities.md) for more details.

core/testing.md

Lines changed: 9 additions & 207 deletions
Original file line numberDiff line numberDiff line change
@@ -1,211 +1,13 @@
1-
# Testing Utilities
1+
# Testing the API
22

3-
API Platform provides a set of useful utilities dedicated to API testing.
4-
For an overview of how to test an API Platform app, be sure to read [the testing cookbook first](../symfony/testing.md).
3+
Once your API is up and running, it's crucial to write tests to ensure it is bug-free and to prevent future regressions.
4+
A good practice is to follow a [Test-Driven Development (TDD)](https://martinfowler.com/bliki/TestDrivenDevelopment.html)
5+
approach, where tests are written before the production code.
56

6-
<p align="center" class="symfonycasts"><a href="https://symfonycasts.com/screencast/api-platform-security/api-tests?cid=apip"><img src="../symfony/images/symfonycasts-player.png" alt="Test and Assertions screencast"><br>Watch the API Tests & Assertions screencast</a></p>
7+
API Platform provides a set of helpful testing utilities to write unit tests, functional tests, and to create
8+
[test fixtures](https://en.wikipedia.org/wiki/Test_fixture#Software).
79

8-
## The Test HttpClient
10+
## Testing Documentations
911

10-
API Platform provides its own implementation of the [Symfony HttpClient](https://symfony.com/doc/current/components/http_client.html)'s interfaces, tailored to be used directly in [PHPUnit](https://phpunit.de/) test classes.
11-
12-
While all the convenient features of Symfony HttpClient are available and usable directly, under the hood the API Platform implementation manipulates [the Symfony HttpKernel](https://symfony.com/doc/current/components/http_kernel.html) directly to simulate HTTP requests and responses.
13-
This approach results in a huge performance boost compared to triggering real network requests.
14-
It also allows access to the [Symfony HttpKernel](https://symfony.com/doc/current/components/http_kernel.html) and to all your services via the [Dependency Injection Container](https://symfony.com/doc/current/testing.html#accessing-the-container).
15-
Reuse them to run, for instance, SQL queries or requests to external APIs directly from your tests.
16-
17-
Install the `symfony/http-client` and `symfony/browser-kit` packages to enabled the API Platform test client:
18-
19-
```console
20-
docker compose exec php \
21-
composer require symfony/browser-kit symfony/http-client
22-
```
23-
24-
To use the testing client, your test class must extend the `ApiTestCase` class:
25-
26-
```php
27-
<?php
28-
// api/tests/BooksTest.php
29-
30-
namespace App\Tests;
31-
32-
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
33-
34-
class BooksTest extends ApiTestCase
35-
{
36-
public function testGetCollection(): void
37-
{
38-
$response = static::createClient()->request('GET', '/books');
39-
// your assertions here...
40-
}
41-
}
42-
```
43-
44-
Refer to [the Symfony HttpClient documentation](https://symfony.com/doc/current/components/http_client.html) to discover all the features of the client (custom headers, JSON encoding and decoding, HTTP Basic and Bearer authentication and cookies support, among other things).
45-
46-
Note that you can create your own test case class extending the ApiTestCase. For example to set up a Json Web Token authentication:
47-
48-
```php
49-
<?php
50-
// api/tests/AbstractTest.php
51-
namespace App\Tests;
52-
53-
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
54-
use ApiPlatform\Symfony\Bundle\Test\Client;
55-
use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;
56-
57-
abstract class AbstractTest extends ApiTestCase
58-
{
59-
private ?string $token = null;
60-
61-
use RefreshDatabaseTrait;
62-
63-
public function setUp(): void
64-
{
65-
self::bootKernel();
66-
}
67-
68-
protected function createClientWithCredentials($token = null): Client
69-
{
70-
$token = $token ?: $this->getToken();
71-
72-
return static::createClient([], ['headers' => ['authorization' => 'Bearer '.$token]]);
73-
}
74-
75-
/**
76-
* Use other credentials if needed.
77-
*/
78-
protected function getToken($body = []): string
79-
{
80-
if ($this->token) {
81-
return $this->token;
82-
}
83-
84-
$response = static::createClient()->request('POST', '/login', ['json' => $body ?: [
85-
'username' => '[email protected]',
86-
'password' => '$3cr3t',
87-
]]);
88-
89-
$this->assertResponseIsSuccessful();
90-
$data = $response->toArray();
91-
$this->token = $data['token'];
92-
93-
return $data['token'];
94-
}
95-
}
96-
```
97-
98-
Use it by extending the `AbstractTest` class. For example this class tests the `/users` resource accessibility where only the admin can retrieve the collection:
99-
100-
```php
101-
<?php
102-
namespace App\Tests;
103-
104-
final class UsersTest extends AbstractTest
105-
{
106-
public function testAdminResource()
107-
{
108-
$response = $this->createClientWithCredentials()->request('GET', '/users');
109-
$this->assertResponseIsSuccessful();
110-
}
111-
112-
public function testLoginAsUser()
113-
{
114-
$token = $this->getToken([
115-
'username' => '[email protected]',
116-
'password' => '$3cr3t',
117-
]);
118-
119-
$response = $this->createClientWithCredentials($token)->request('GET', '/users');
120-
$this->assertJsonContains(['description' => 'Access Denied.']);
121-
$this->assertResponseStatusCodeSame(403);
122-
}
123-
}
124-
```
125-
126-
## API Test Assertions
127-
128-
In addition to [the built-in ones](https://phpunit.readthedocs.io/en/latest/assertions.html), API Platform provides convenient PHPUnit assertions dedicated to API testing:
129-
130-
```php
131-
<?php
132-
// api/tests/MyTest.php
133-
134-
namespace App\Tests;
135-
136-
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
137-
138-
class MyTest extends ApiTestCase
139-
{
140-
public function testSomething(): void
141-
{
142-
// static::createClient()->request(...);
143-
144-
// Asserts that the returned JSON is equal to the passed one
145-
$this->assertJsonEquals(/* a JSON document as an array or as a string */);
146-
147-
// Asserts that the returned JSON is a superset of the passed one
148-
$this->assertJsonContains(/* a JSON document as an array or as a string */);
149-
150-
// justinrainbow/json-schema must be installed to use the following assertions
151-
152-
// Asserts that the returned JSON matches the passed JSON Schema
153-
$this->assertMatchesJsonSchema(/* a JSON Schema as an array or as a string */);
154-
155-
// Asserts that the returned JSON is validated by the JSON Schema generated for this resource by API Platform
156-
157-
// For collections
158-
$this->assertMatchesResourceCollectionJsonSchema(YourApiResource::class);
159-
// And for items
160-
$this->assertMatchesResourceItemJsonSchema(YourApiResource::class);
161-
}
162-
}
163-
```
164-
165-
There is also a method to find the IRI matching a given resource and some criteria:
166-
167-
```php
168-
<?php
169-
// api/tests/BooksTest.php
170-
171-
namespace App\Tests;
172-
173-
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
174-
175-
class BooksTest extends ApiTestCase
176-
{
177-
public function testFindBook(): void
178-
{
179-
// Asserts that the returned JSON is equal to the passed one
180-
$iri = $this->findIriBy(Book::class, ['isbn' => '9780451524935']);
181-
static::createClient()->request('GET', $iri);
182-
$this->assertResponseIsSuccessful();
183-
}
184-
}
185-
```
186-
187-
## HTTP Test Assertions
188-
189-
All test assertions provided by Symfony (assertions for status codes, headers, cookies, XML documents...) can be used out of the box with the API Platform test client:
190-
191-
```php
192-
<?php
193-
// api/tests/BooksTest.php
194-
195-
namespace App\Tests;
196-
197-
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
198-
199-
class BooksTest extends ApiTestCase
200-
{
201-
public function testGetCollection(): void
202-
{
203-
static::createClient()->request('GET', '/books');
204-
205-
$this->assertResponseIsSuccessful();
206-
$this->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
207-
}
208-
}
209-
```
210-
211-
[Check out the dedicated Symfony documentation entry](https://symfony.com/doc/current/testing/functional_tests_assertions.html).
12+
- If you are using API Platform with Symfony, refer to the [Testing the API with Symfony](/symfony/testing.md) documentation.
13+
- If you are using API Platform with Laravel, refer to the [Testing the API with Laravel](/laravel/testing.md) documentation.

0 commit comments

Comments
 (0)