brilo-example/tests/Unit/Service/Remote/BriloApiCommentsTest.php

99 lines
3.2 KiB
PHP
Raw Normal View History

2024-07-29 16:50:58 +00:00
<?php
declare(strict_types=1);
namespace App\Tests\Unit\Service\Remote;
use App\Entity\Remote\Brilo\Comments\Comment;
use App\Entity\Remote\Brilo\Posts\Post;
use App\Service\Remote\BriloApiComments;
use App\Service\Remote\BriloApiPosts;
use App\Service\Remote\BriloRemoteApiException;
use App\Tests\Common\LoggerTrait;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;
use Symfony\Component\Serializer\SerializerInterface;
class BriloApiCommentsTest extends TestCase
{
use LoggerTrait;
private const array API_COMMENTS_LIST = [
[
"postId" => 1,
"id" => 1,
"name" => "id labore ex et quam laborum",
"email" => "Eliseo@gardner.biz",
"body" => "laudantium enim quasi est quidem magnam voluptate ipsam eos
tempora quo necessitatibus
dolor quam autem quasi
reiciendis et nam sapiente accusantium"
],
[
"postId" => 1,
"id" => 2,
"name" => "quo vero reiciendis velit similique earum",
"email" => "Jayne_Kuhic@sydney.com",
"body" => "est natus enim nihil est dolore omnis voluptatem numquam
et omnis occaecati quod ullam at
voluptatem error expedita pariatur
nihil sint nostrum voluptatem reiciendis et"
]
];
public function testCommentsListSuccess(): void
{
$testCommentsList = $this->buildTestCommentsList();
$serializer = $this->createMock(SerializerInterface::class);
$serializer
->expects($this->once())
->method('deserialize')
->with(
json_encode(self::API_COMMENTS_LIST),
Comment::class . '[]',
'json'
)->willReturn($testCommentsList);
$response = new JsonMockResponse(self::API_COMMENTS_LIST);
$mockedClient = new MockHttpClient($response);
$briloApiPosts = new BriloApiComments($mockedClient, $this->getLogger(), $serializer);
$this->assertEquals($testCommentsList, $briloApiPosts->getComments());
}
public function testInvalidHttpCodeReturned(): void
{
$serializer = $this->createMock(SerializerInterface::class);
$serializer
->expects($this->never())
->method('deserialize');
$response = new JsonMockResponse(self::API_COMMENTS_LIST, [
'http_code' => 401,
]);
$mockedClient = new MockHttpClient(function () use ($response) {
return $response;
});
$this->expectException(BriloRemoteApiException::class);
$briloApiPosts = new BriloApiComments($mockedClient, $this->getLogger(), $serializer);
$briloApiPosts->getComments();
}
/**
* @return Comment[]
*/
public function buildTestCommentsList(): array
{
// Convert self::API_POSTS_LIST to Post[] and return it
return array_map(function ($postData) {
return new Comment(
$postData['id'],
$postData['postId'],
$postData['name'],
$postData['email'],
$postData['body']
);
}, self::API_COMMENTS_LIST);
}
}