Skip to content

Instantly share code, notes, and snippets.

@timoschinkel
Created July 3, 2019 13:34
Show Gist options
  • Save timoschinkel/29962f13331dc0bec77d62a7ebd3ee22 to your computer and use it in GitHub Desktop.
Save timoschinkel/29962f13331dc0bec77d62a7ebd3ee22 to your computer and use it in GitHub Desktop.
Testing with immutable PSR-7 objects and Prophecy
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
final class ApiKeyMiddlewareTest extends TestCase
{
use Psr7Factories;
/**
* Tests:
*
* ```
* public function process(RequestInterface $request, ClientInterface $client): ResponseInterface
* {
* $request = $request
* ->withHeader('X-Api-Key', $this->apiKey)
* ->withHeader('Accept', 'application/json');
*
* return $client->sendRequest($request);
* }
* ```
*/
public function testApiKeyIsAddedAndResponseIsReturned(): void
{
$apiKey = 'api key';
$requestWithApiKey = $this->prophesize(RequestInterface::class)->reveal();
$requestWithAcceptHeader = $this->prophesize(RequestInterface::class);
$requestWithAcceptHeader
->withHeader('X-Api-Key', $apiKey)
->shouldBeCalled()
->willReturn($requestWithApiKey);
$request = $this->prophesize(RequestInterface::class);
$request
->withHeader('Accept', 'application/json')
->shouldBeCalled()
->willReturn($requestWithAcceptHeader->reveal());
$client = $this->prophesize(ClientInterface::class);
$client
->sendRequest(Argument::is($requestWithApiKey))
->shouldBeCalled()
->willReturn($this->prophesize(ResponseInterface::class)->reveal());
$middleware = new ApiKeyMiddleware($apiKey);
$response = $middleware->process($request->reveal(), $client->reveal());
self::assertInstanceOf(ResponseInterface::class, $response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment