PHP code example of fansipan / mock-client

1. Go to this page and download the library: Download fansipan/mock-client library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

fansipan / mock-client example snippets


use Fansipan\Mock\MockClient;

$client = new MockClient();
$response = $client->sendRequest($request);

use Fansipan\Mock\MockClient;
use Fansipan\Mock\MockResponse;

$client = new MockClient(MockResponse::create('', 500));

use Fansipan\Mock\MockResponse;

MockResponse::create(['name' => 'John', 'age' => 30], 201, ['X-Custom-Header' => 'foo']);

use Fansipan\Mock\MockResponse;

MockResponse::fixture(__DIR__.'/fixtures/user.json');

use Fansipan\Mock\MockClient;
use Fansipan\Mock\MockResponse;

$client = new MockClient([
    MockResponse::make(['name' => 'foo'], 200),
    MockResponse::make(['name' => 'bar'], 201),
    MockResponse::make(['error' => 'Server Error'], 500),
]);

$client->sendRequest($firstRequest); // Will return with `['name' => 'foo']` and status `200`
$client->sendRequest($secondRequest); // Will return with `['name' => 'bar']` and status `200`
$client->sendRequest($thirdRequest); // Will return with `['error' => 'Server Error']` and status `500`

use Fansipan\Mock\MockResponse;
use Fansipan\Mock\ScopingMockClient;

new ScopingMockClient([
    // Stub a JSON response for GitHub endpoints...
    'github.com/*' => MockResponse::create(['foo' => 'bar'], 200),

    // Stub a string response for Google endpoints...
    'google.com/*' => MockResponse::create('Hello World', 200, $headers),

    // Stub a string response for all other endpoints...
    '*' => MockResponse::create('Hello World', 200, $headers),
]);

use Fansipan\Mock\MockResponse;
use Fansipan\Mock\ScopingMockClient;

new ScopingMockClient([
    // Stub sequence JSON responses for GitHub endpoints...
    'github.com/*' => [
        MockResponse::create(['foo' => 'bar']),
        MockResponse::create(['error' => 'Server Error'], 500),
    ],

    // Stub sequence responses for Google endpoints...
    'google.com/*' => [
        MockResponse::create('Hello World', 200, $headers),
        MockResponse::create(['baz' => 'qux']),
    ],
]);

use Fansipan\Mock\MockClient;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

$client = new MockClient();

$request = $requestFactory->createRequest('GET', 'http://example.com/users/1');
$client->sendRequest($request);

$client->assertSent('users/*');

$client->assertSent(function (RequestInterface $request, ResponseInterface $response): bool {
    return $request->getMethod() === 'GET'
        && (string) $request->getUri() === 'http://example.com/users/1'
        && $response->getStatusCode() === 200;
});