-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathBaseTestCase.php
More file actions
76 lines (64 loc) · 2.26 KB
/
BaseTestCase.php
File metadata and controls
76 lines (64 loc) · 2.26 KB
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
<?php
/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Geocoder\IntegrationTest;
use Http\Client\Curl\Client as HttplugClient;
use Http\Mock\Client as MockedHttpClient;
use Nyholm\Psr7\Response;
use PHPUnit\Framework\TestCase;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
abstract class BaseTestCase extends TestCase
{
/**
* @return string|null the directory where cached responses are stored
*/
abstract protected function getCacheDir();
/**
* Get a real HTTP client. If a cache dir is set to a path it will use cached responses.
*/
protected function getHttpClient(?string $apiKey = null): ClientInterface
{
if (null !== $cacheDir = $this->getCacheDir()) {
return new CachedResponseClient(new HttplugClient(), $cacheDir, $apiKey);
} else {
return new HttplugClient();
}
}
/**
* Get a mocked HTTP client that never do calls over the internet. Use this is you want to control the response data.
*/
protected function getMockedHttpClient(?string $body = null, int $statusCode = 200): ClientInterface
{
$client = new MockedHttpClient();
$client->addResponse(new Response($statusCode, [], $body));
return $client;
}
/**
* Get a mocked HTTP client where you may do tests on the request.
*/
protected function getMockedHttpClientCallback(callable $requestCallback): ClientInterface
{
$client = $this->getMockBuilder(ClientInterface::class)->getMock();
$client
->expects($this->once())
->method('sendRequest')
->willReturnCallback(function (RequestInterface $request) use ($requestCallback) {
$response = $requestCallback($request);
if (!$response instanceof ResponseInterface) {
$response = new Response(200, [], (string) $response);
}
return $response;
});
return $client;
}
}