PHPackages                             fansipan/mock-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. fansipan/mock-client

ActiveLibrary[HTTP &amp; Networking](/categories/http)

fansipan/mock-client
====================

PSR-18 Mock HTTP Client

1.2.0(1y ago)17.8k↓20.7%5MITPHPPHP ^7.2.5|^8.0

Since Mar 24Pushed 1y ago1 watchersCompare

[ Source](https://github.com/phanxipang/mock-client)[ Packagist](https://packagist.org/packages/fansipan/mock-client)[ Docs](https://github.com/phanxipang/mock-client)[ RSS](/packages/fansipan-mock-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (8)Versions (11)Used By (5)

Fansipan Mock HTTP Client
=========================

[](#fansipan-mock-http-client)

[![Latest Version on Packagist](https://camo.githubusercontent.com/9a07532acd58adf33a0495e9767e8fab48ba78de67ea6376486adcccb3512deb/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f66616e736970616e2f6d6f636b2d636c69656e742e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/fansipan/mock-client)[![Github Actions](https://camo.githubusercontent.com/37b46965d42bbf8f141a75ce1745d9fa59dc98e280e7aa70237b76dcb798b581/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7068616e786970616e672f6d6f636b2d636c69656e742f74657374696e672e796d6c3f6272616e63683d6d61696e266c6162656c3d616374696f6e73266c6f676f3d676974687562267374796c653d666f722d7468652d6261646765)](https://github.com/jenky/phanxipang/mock-client/actions)[![Codecov](https://camo.githubusercontent.com/4fd1b3d45705beae418874f664a488ec38cfc2bfbec600a07ffb54ddefa21801/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f7068616e786970616e672f6d6f636b2d636c69656e743f6c6f676f3d636f6465636f76267374796c653d666f722d7468652d6261646765)](https://codecov.io/gh/phanxipang/mock-client)[![Total Downloads](https://camo.githubusercontent.com/bfb55eb131792b267a1ffbb047090de7def86192c190aa9e8dc937d1514fa24a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f66616e736970616e2f6d6f636b2d636c69656e742e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/fansipan/mock-client)[![Software License](https://camo.githubusercontent.com/9897f4467850972a38c7db9a4d38280b8fcdac0ada00e9c8c0a72ecfa8551653/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666f722d7468652d6261646765)](LICENSE.md)

Fansipan mock HTTP client is [PSR-18 Client](https://www.php-fig.org/psr/psr-18/) implementation that provides ability send test requests with fake responses.

The `MockClient` accepts `Psr\Http\Message\ResponseInterface` which when used on a request, will respond with a fake response without actually sending a real request to the web. This helps speed up tests massively and can help you test your application for different API response scenarios, like a 404 error or 500 error.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require fansipan/mock-client
```

Usage
-----

[](#usage)

### Creating Mock Client

[](#creating-mock-client)

```
use Fansipan\Mock\MockClient;

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

By default `MockClient` will always return `200 - OK` status code with empty body. If you want to return a different response, create a `Psr\Http\Message\ResponseInterface` instance and pass it as constructor argument. You can use `MockResponse` to quickly create a fake response.

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

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

### Faking Response

[](#faking-response)

The `MockResponse` class is used to create fake responses. It can accept a body, status, and headers. These properties will be populated in the fake response. The response body accepts an array for a JSON body or plain strings to simulate other responses, like XML.

```
use Fansipan\Mock\MockResponse;

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

> You don't have to add `['Content-Type' => 'application/json']` header if your body is array.

If you have fixture data and don't want to create response manually, you can also use `fixture` method to create a response.

```
use Fansipan\Mock\MockResponse;

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

> If your fixture is a JSON or XML file, there's no need to add the `Content-Type` header manually.

#### Faking Response Sequences

[](#faking-response-sequences)

Sequence faking allows you to define a number of fake responses in a specific order. It will pull out the next response in the sequence, removing it from the sequence. Each response can only be consumed once. When all the responses in a response sequence have been consumed, any further requests will cause the response sequence to throw an exception.

```
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`
```

### Faking Specific URLs

[](#faking-specific-urls)

Alternatively, you may use `ScopingMockClient` and pass an array to the constructor argument. The array's keys should represent URL patterns that you wish to fake and their associated responses. The `*` character may be used as a wildcard character. Any requests made to URLs that have not been faked will actually be executed.

```
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),
]);
```

[Sequence Faking](#faking-response-sequences) also works with `ScopingMockClient`

```
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']),
    ],
]);
```

### Adding Expectations

[](#adding-expectations)

When using faking responses, it's important to be able to check that a specific make request was sent and with the correct data, and headers. `MockClient` &amp; `ScopingMockClient` provide you with various ways to add expectations to your tests.

#### Available Expectations

[](#available-expectations)

- `assertSent`
- `assetNotSend`
- `assertNothingSent`
- `assertSentCount`

The `assertSent` / `assertNotSent` are the two most powerful expectation methods. They can accept a URL pattern or even a closure where you define if a request/response is what you expect.

```
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;
});
```

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CODE\_OF\_CONDUCT](CODE_OF_CONDUCT.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Lynh](https://github.com/jenky)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance38

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~74 days

Recently: every ~140 days

Total

9

Last Release

554d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/783e915bb411d566e8f1035f197842db5e870a2a995b3943bcbe5db2f9abf09b?d=identicon)[Milano](/maintainers/Milano)

---

Top Contributors

[![jenky](https://avatars.githubusercontent.com/u/1808758?v=4)](https://github.com/jenky "jenky (29 commits)")

---

Tags

http-clientmock-clientpsr-18http clientmock-http-clientfansipan

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/fansipan-mock-client/health.svg)

```
[![Health](https://phpackages.com/badges/fansipan-mock-client/health.svg)](https://phpackages.com/packages/fansipan-mock-client)
```

###  Alternatives

[kriswallsmith/buzz

Lightweight HTTP client

2.0k31.3M443](/packages/kriswallsmith-buzz)[laudis/neo4j-php-client

Neo4j-PHP-Client is the most advanced PHP Client for Neo4j

184616.9k31](/packages/laudis-neo4j-php-client)[phpro/http-tools

HTTP tools for developing more consistent HTTP implementations.

28137.8k](/packages/phpro-http-tools)[simpod/clickhouse-client

PHP ClickHouse Client

19116.7k](/packages/simpod-clickhouse-client)[art4/requests-psr18-adapter

Use WordPress/Requests as a PSR-18 HTTP client

153.3k](/packages/art4-requests-psr18-adapter)[amphp/http-client-psr7

PSR-7 adapter for Amp's HTTP client.

1454.7k4](/packages/amphp-http-client-psr7)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
