PHPackages                             jshayes/fake-requests - 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. jshayes/fake-requests

ActiveLibrary

jshayes/fake-requests
=====================

A package to make it easier to test with guzzle.

v3.0(6y ago)751.9k1[1 PRs](https://github.com/jshayes/fake-requests/pulls)3MITPHP

Since Aug 6Pushed 1y agoCompare

[ Source](https://github.com/jshayes/fake-requests)[ Packagist](https://packagist.org/packages/jshayes/fake-requests)[ RSS](/packages/jshayes-fake-requests/feed)WikiDiscussions master Synced 2mo ago

READMEChangelog (8)Dependencies (6)Versions (10)Used By (3)

[![Build Status](https://camo.githubusercontent.com/7ef53ada9f8a8f422251d83964272db6e651f38d240bafffc5d5c51789a98864/68747470733a2f2f7472617669732d63692e6f72672f6a7368617965732f66616b652d72657175657374732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/jshayes/fake-requests) [![Coverage Status](https://camo.githubusercontent.com/846ab8abdf9d1fe4c3c5ab390239066d60e7ab28f3969be5ca5b9d36086b1c2e/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6a7368617965732f66616b652d72657175657374732f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/jshayes/fake-requests?branch=master)

fake-requests
=============

[](#fake-requests)

A simple package to make testing with guzzle easier

Basic usage
-----------

[](#basic-usage)

You can register expected calls to the `MockHandler`. The mock handler has methods for each http request type.

```
use JSHayes\FakeRequests\MockHandler;
use JSHayes\FakeRequests\ClientFactory;

public function test()
{
    $factory = new ClientFactory();
    $factory->setHandler($mockHandler = new MockHandler());

    $mockHandler->get('/get-request');
    $mockHandler->post('/post-request');

    $factory->make()->get('/get-request');
    $factory->make()->post('/post-request');
}
```

This simple example creates two expectations. The first is a `GET` request with the URL path of `/get-request`. The second is a `POST` request with a URL path of `/post-request`. The client is then resolved out of the factory, and `GET` and `POST` requests are made for each expectation.

The `ClientFactory` can be used to resolve guzzle client instances. You can bind a handler to the factory so that when it resolves the guzzle client it will swap out the default handler with the one that you have specified. It will also keep the registered middleware intact in the case that you are using the `HandlerStack`.

Once an expectation is met, it is removed from the handler. So if you make the same request twice you have to add two separate expectations.

You can also use the following alternative syntax

```
use JSHayes\FakeRequests\MockHandler;
use JSHayes\FakeRequests\ClientFactory;

public function test()
{
    $factory = new ClientFactory();
    $factory->setHandler($mockHandler = new MockHandler());

    $mockHandler->expects('get', '/get-request');
    $mockHandler->expects('post', '/post-request');

    $factory->make()->get('/get-request');
    $factory->make()->post('/post-request');
}
```

This example sets up the same expectations as the example above.

You can also specify hosts in the uri, rather than just the path. This can allow you to ensure the correct service is being hit in the case that you talk to more than one remote service.

```
use JSHayes\FakeRequests\MockHandler;
use JSHayes\FakeRequests\ClientFactory;

public function test()
{
    $factory = new ClientFactory();
    $factory->setHandler($mockHandler = new MockHandler());

    $mockHandler->expects('get', 'https://test.dev/get-request');

    $factory->make()->get('https://test.dev/get-request');
}
```

Inspecting the request
----------------------

[](#inspecting-the-request)

If you need to make assertions on the request that created, or the options that are provided, you can use the `inspectRequest` method. This method receives an instance of `\Psr\Http\Message\RequestInterface` as the first parameter.

```
$mockHandler->get('/get-request')->inspectRequest(function (RequestInterface $request, array $options) {
    // Make assertions on the request or options here
});
```

Alternatively, you can use the `getRequest` method to get the request off the `RequestHandler` after it has been handled. This request is an instance of `\JSHayes\FakeRequests\Request`, which is a decorator around the `\Psr\Http\Message\RequestInterface`. This decorator exposes a few assertion helper functions. For some examples, see the following

```
$expectation = $mockHandler->get('/get-request');
$factory->make()->get('/get-request');
$request = $expectation->getRequest();
$request->assertBodyEquals('');
```

Note that the request is null until one has been handled by the handler.

Extending the request
---------------------

[](#extending-the-request)

If you ever want to add some custom helper methods to the request, you can extend the request using the `extendRequest` method. This method accepts a string that is the class name of the request class you would like to use. This extended request class must extend `JSHayes\FakeRequests\Request`. Since the `JSHayes\FakeRequests\Request` class extends `PHPUnit\Framework\Assert`, your extended request class will have access to PHPUnit's assertion methods.

For example, you can create an extended request similar to the following

```
use JSHayes\FakeRequests\Request;

class ExtendedRequest extends Request
{
    /**
     * This is an example method in an extended request. These extended requests
     * can be used to add assertion helpers to make testing request flows easier
     *
     * @return void
     */
    public function assertExample(): void
    {
        $this->assertTrue(true);
    }
}
```

This extended request can be user as follows

```
// Register the extended request with the mock handler
$mockHandler->extendRequest(ExtendedRequest::class);

$expectation = $mockHandler->get('/get-request');
$factory->make()->get('/get-request');

// Getting the request from the expectation will return the extended request
$request = $expectation->getRequest();
$request->assertExample();
```

Alternatively, if you do not wish to extend every request that the mock handler handles, you can extend requests on the request handler itself.

```
$expectation1 = $mockHandler->get('/get-request1')->extendRequest(ExtendedRequest::class);
$expectation2 = $mockHandler->get('/get-request2');
$factory->make()->get('/get-request1');
$factory->make()->get('/get-request2');

// Getting the request from the expectation will return the extended request
$request = $expectation1->getRequest();
$request->assertExample();

// Getting the request for the second expectation will not return the extended request, since
// we only extended the request on the first expectation. So, the assertExample method will
// not be available here.
$request->expectation2->getRequest();
```

Customizing the response
------------------------

[](#customizing-the-response)

There are a few ways to create a custom response for each expectation. When you create a custom response, that response is what will be returned to the guzzle client when the request expectation is met. The three ways to customize the response are as follows.

The first method is by passing in the parameters for the request. The first parameter is the status code. The second is the body of the response. The third is the array of headers to add to the response.

```
$mockHandler->get('/test')->respondWith(200, 'body', ['header' => 'value]);
```

The second method is by creating a request that implements `\Psr\Http\Message\ResponseInterface`.

```
$mockHandler->get('/test')->respondWith(new Response(200, ['header' => 'value'], 'body'));
```

The third method is by passing a callback to `respondWith`. This callback will receive an instance of `\JSHayes\FakeRequests\ResponseBuilder`

```
$mockHandler->get('/test')->respondWith(function (ResponseBuilder $builder) {
    $builder->status(200);
    $builder->body('body');
    $builder->headers(['header' => 'values']);
});
```

Controlling when a handler should be handled
--------------------------------------------

[](#controlling-when-a-handler-should-be-handled)

If you would like more control over when a `RequestHandler` handles a given request, you can use the `when` method. This method receives an instance of `\Psr\Http\Message\RequestInterface` as the first parameter.

```
$mockHandler->get('/test')->when(function (RequestInterface $request, array $options) {
    return true;
});
```

The handler will only handle the request when the method and uri match, and when the `when` callback returns true.

Allowing Unexpected Calls
-------------------------

[](#allowing-unexpected-calls)

Sometimes you might want the `MockHandler` to not error when it receives calls to endpoint that it did not expect calls to. In this case you can use the `allowUnexpectedCalls` method on the `MockHandler`

```
$mockHandler->allowUnexpectedCalls();
$client->get('/test');
```

In this example the `GET` request to `/test` will respond with a generic 200 response.

Testing with Laravel
--------------------

[](#testing-with-laravel)

This package also comes with a trait to make testing with Laravel a bit easier.

```
use JSHayes\FakeRequests\Traits\Laravel\FakeRequests;

class SomeTest extends TestCase
{
    use FakeRequests;

    /**
     * @test
     */
    public function some_test()
    {
        $handler = $this->fakeRequests();
        // Add expectations to the handler
    }
}
```

In this example, the `fakeRequests` method created the `MockHandler` for you. It will also bind it to the `ClientFactory` and bind the `ClientFactory` instance to the IOC. If you resolve the `ClientFactory` out of the IOC in you code, this trait will allow you to easily use the `MockHandler` in all of you guzzle client instances.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance26

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity69

Established project with proven stability

 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 ~127 days

Recently: every ~185 days

Total

8

Last Release

2306d ago

Major Versions

v0.1 → v1.02017-08-09

v1.1 → v2.02018-01-05

v2.3 → v3.02020-01-16

### Community

Maintainers

![](https://www.gravatar.com/avatar/424a6f770c0e4b9da8019eb907aed8222b00a6d1d0df6f922694d1c1870ca108?d=identicon)[jshayes](/maintainers/jshayes)

---

Top Contributors

[![JaskirtPooni](https://avatars.githubusercontent.com/u/3004458?v=4)](https://github.com/JaskirtPooni "JaskirtPooni (5 commits)")

###  Code Quality

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/jshayes-fake-requests/health.svg)

```
[![Health](https://phpackages.com/badges/jshayes-fake-requests/health.svg)](https://phpackages.com/packages/jshayes-fake-requests)
```

###  Alternatives

[s-ichikawa/laravel-sendgrid-driver

This library adds a 'sendgrid' mail driver to Laravel.

4139.3M1](/packages/s-ichikawa-laravel-sendgrid-driver)[stechstudio/laravel-zipstream

A fast and simple streaming zip file downloader for Laravel.

4633.7M3](/packages/stechstudio-laravel-zipstream)[laravel-notification-channels/microsoft-teams

A Laravel Notification Channel for Microsoft Teams

1603.0M7](/packages/laravel-notification-channels-microsoft-teams)[spatie/laravel-export

Create a static site bundle from a Laravel app

646127.9k5](/packages/spatie-laravel-export)[erag/laravel-disposable-email

A Laravel package to detect and block disposable email addresses.

226102.4k](/packages/erag-laravel-disposable-email)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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