-
-
Notifications
You must be signed in to change notification settings - Fork 901
/
Copy pathtest-your-api.php
78 lines (67 loc) · 2.5 KB
/
test-your-api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
// ---
// slug: test-your-api
// name: Test your API
// executable: true
// position: 7
// tags: tests
// ---
namespace App\Tests {
use ApiPlatform\Playground\Test\TestGuideTrait;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\ApiResource\Book;
// API Platform [testing utilities](/docs/core/testing/) provides an [ApiTestCase](/docs/reference/Symfony/Bundle/Test/ApiTestCase/)
// that allows you to send an HTTP Request, and to perform assertions on the Response.
final class BookTest extends ApiTestCase
{
use TestGuideTrait;
public function testBookDoesNotExists(): void
{
// For starters we can get an [HTTP Client](/docs/reference/Symfony/Bundle/Test/Client/) with the `createClient` method.
$client = static::createClient();
// Then, issue an HTTP request via this client, as we didn't load any data we'd expect this to send a 404 Not found.
$client->request(method: 'GET', url: '/books/1');
$this->assertResponseStatusCodeSame(404);
// Our API uses the JSON Problem specification on every thrown exception.
$this->assertJsonContains([
'detail' => 'Not Found',
]);
}
public function testGetCollection(): void
{
$response = static::createClient()->request(method: 'GET', url: '/books');
// We provide assertions based on your resource's JSON Schema to save time asserting that the data
// matches an expected format, for example here with a collection.
$this->assertMatchesResourceCollectionJsonSchema(Book::class);
// PHPUnit default assertions are also available.
$this->assertCount(0, $response->toArray()['member']);
}
}
}
namespace App\ApiResource {
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\CollectionOperationInterface;
#[ApiResource(provider: [Book::class, 'provide'])]
class Book
{
public string $id;
public static function provide($operation)
{
return $operation instanceof CollectionOperationInterface ? [] : null;
}
}
}
// # Test your API
namespace App\Playground {
use Symfony\Component\HttpFoundation\Request;
function request(): Request
{
return Request::create(
uri: '/books/1',
method: 'GET',
server: [
'HTTP_ACCEPT' => 'application/ld+json',
]
);
}
}