Skip to content

Commit 62f6795

Browse files
committed
Callable mock for more priceise mocking
1 parent e749ab4 commit 62f6795

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/CallableMock.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace ApiClients\Middleware\Mock;
4+
5+
use Psr\Http\Message\RequestInterface;
6+
use Psr\Http\Message\ResponseInterface;
7+
8+
final class CallableMock implements MockInterface
9+
{
10+
/** @var callable */
11+
private $matcher;
12+
13+
/** @var ResponseInterface */
14+
private $response;
15+
16+
public function __construct(callable $matcher, ResponseInterface $response)
17+
{
18+
$this->matcher = $matcher;
19+
$this->response = $response;
20+
}
21+
22+
public function match(RequestInterface $request): bool
23+
{
24+
return ($this->matcher)($request);
25+
}
26+
27+
public function response(RequestInterface $request): ResponseInterface
28+
{
29+
return $this->response;
30+
}
31+
}

tests/CallableMockTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php declare(strict_types=1);
2+
3+
namespace ApiClients\Tests\Middleware\Mock;
4+
5+
use ApiClients\Middleware\Mock\CallableMock;
6+
use ApiClients\Tools\TestUtilities\TestCase;
7+
use Psr\Http\Message\RequestInterface;
8+
use RingCentral\Psr7\Request;
9+
use RingCentral\Psr7\Response;
10+
11+
/**
12+
* @internal
13+
*/
14+
class CallableMockTest extends TestCase
15+
{
16+
public function testMatch(): void
17+
{
18+
$response = new Response();
19+
$mock = new CallableMock(function (RequestInterface $request) {
20+
return $request->getUri()->getPath() === '/path';
21+
}, $response);
22+
self::assertTrue($mock->match(new Request('GET', '/path')));
23+
}
24+
25+
public function testNoMatch(): void
26+
{
27+
$response = new Response();
28+
$mock = new CallableMock(function (RequestInterface $request) {
29+
return $request->getUri()->getPath() === '/';
30+
}, $response);
31+
self::assertFalse($mock->match(new Request('GET', '/path')));
32+
}
33+
34+
public function testResponse(): void
35+
{
36+
$response = new Response();
37+
$mock = new CallableMock(function (RequestInterface $request) {
38+
return $request->getUri()->getPath() === '/path';
39+
}, $response);
40+
self::assertSame($response, $mock->response(new Request('GET', '/path')));
41+
}
42+
}

0 commit comments

Comments
 (0)