PHPackages                             bentools/test-http-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. [Testing &amp; Quality](/categories/testing)
4. /
5. bentools/test-http-client

ActiveLibrary[Testing &amp; Quality](/categories/testing)

bentools/test-http-client
=========================

Test Symfony applications with HttpClient interface without a real HTTP server

1.0.0(3mo ago)062MITPHPPHP &gt;=8.2CI passing

Since Feb 6Pushed 3mo agoCompare

[ Source](https://github.com/bpolaszek/test-http-client)[ Packagist](https://packagist.org/packages/bentools/test-http-client)[ RSS](/packages/bentools-test-http-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (10)Versions (2)Used By (0)

Test HTTP Client for Symfony
============================

[](#test-http-client-for-symfony)

[![Tests](https://github.com/bpolaszek/test-http-client/actions/workflows/tests.yml/badge.svg)](https://github.com/bpolaszek/test-http-client/actions/workflows/tests.yml)[![Code Coverage](https://camo.githubusercontent.com/b5844f2609232785b5d7ae21d5084675d0b7bfdd04d475efa45989c515726a3a/68747470733a2f2f636f6465636f762e696f2f67682f62706f6c61737a656b2f746573742d687474702d636c69656e742f67726170682f62616467652e7376673f746f6b656e3d73467938733346616848)](https://codecov.io/gh/bpolaszek/test-http-client)

Test your Symfony / Api-Platform routes and controllers with `symfony/http-client`.

This package provides a test implementation of Symfony's `HttpClientInterface` that uses `KernelBrowser` internally, allowing you to test your HTTP endpoints as if you were making real HTTP requests, but without the overhead of running an actual HTTP server.

Compatible with both **PHPUnit** and **Pest**.

Example
-------

[](#example)

```
// src/Controller/HealthController.php
namespace App\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

final readonly class HealthController
{
    #[Route('/health')]
    public function __invoke(): JsonResponse {
        return new JsonResponse(['status' => '😎']);
    }
}
```

### Pest

[](#pest)

```
// tests/Controller/HealthControllerTest.php

use BenTools\TestHttpClient\TestHttpClient;

use function BenTools\Pest\Symfony\inject;

it('works', function () {
    $client  = inject(TestHttpClient::class); // request('GET', '/health');

    expect($response)->toBeSuccessful()
        ->and($response)->toHaveStatusCode(200)
        ->and($response)->toHaveHeader('Content-Type', 'application/json')
        ->and($response)->toHaveJsonStructure(['status'])
        ->and($response['status'])->toBe('😎')
    ;
});
```

### PHPUnit

[](#phpunit)

```
// tests/Controller/HealthControllerTest.php
use BenTools\TestHttpClient\TestHttpClient;

class HealthControllerTest extends WebTestCase
{
    public function testHealth(): void
    {
        $client = static::getContainer()->get(TestHttpClient::class);
        $response = $client->request('GET', '/health');

        $this->assertSame(200, $response->getStatusCode());
        $this->assertContains('application/json', $response->getHeaders()['content-type'] ?? '');
        $this->assertArrayHasKey('status', $response);
        $this->assertEquals('😎', $response['status']);
    }
}
```

Features
--------

[](#features)

- ✅ **Implements `HttpClientInterface`** - Drop-in replacement for real HTTP clients in tests
- ✅ **No HTTP server required** - Uses Symfony's `KernelBrowser` under the hood
- ✅ **Fast integration tests** - Test your API endpoints in milliseconds
- ✅ **Access to internals** - Get the container, profiler, cookies, and more
- ✅ **Pest expectations included** - Custom expectations for testing responses
- ✅ **Full HTTP feature support** - Headers, authentication, JSON, query parameters, etc.

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

[](#installation)

```
composer require --dev bentools/test-http-client
```

Symfony Bundle Integration
--------------------------

[](#symfony-bundle-integration)

For Symfony applications, you can register the bundle to automatically wire the `TestHttpClient` service:

### 1. Register the Bundle

[](#1-register-the-bundle)

Add the bundle to your `config/bundles.php` (only in test environment):

```
// config/bundles.php
return [
    // ... other bundles
    BenTools\TestHttpClient\Bundle\TestHttpClientBundle::class => ['test' => true],
];
```

### 2. Use the Service

[](#2-use-the-service)

Once registered, the `TestHttpClient` service is automatically available in your test environment:

```
use BenTools\TestHttpClient\TestHttpClient;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ApiTest extends WebTestCase
{
    public function testUsersList(): void
    {
        $client = static::getContainer()->get(TestHttpClient::class);
        $response = $client->request('GET', '/api/users');

        $this->assertSame(200, $response->getStatusCode());
    }
}
```

For Pest tests:

```
it('returns users list', function () {
    $client = container()->get(TestHttpClient::class);
    $response = $client->request('GET', '/api/users');

    expect($response)->toHaveStatusCode(200);
});
```

Note

If you prefer to instantiate `TestHttpClient` manually without registering the bundle, you can still do so as shown in the Quick Start section below.

Quick Start
-----------

[](#quick-start)

### With Pest

[](#with-pest)

```
use BenTools\TestHttpClient\TestHttpClient;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

uses(WebTestCase::class);

it('returns users list', function () {
    $client = new TestHttpClient(static::createClient());
    $response = $client->request('GET', '/api/users');

    expect($response)
        ->toHaveStatusCode(200)
        ->toHaveJsonStructure()
        ->toHaveHeader('content-type', 'application/json');

    $data = $response->toArray();
    expect($data)->toHaveKey('users');
});
```

### With PHPUnit

[](#with-phpunit)

```
use BenTools\TestHttpClient\TestHttpClient;

public function testReturnsUsersList(): void
{
    $client = new TestHttpClient(static::createClient());
    $response = $client->request('GET', '/api/users');

    $this->assertSame(200, $response->getStatusCode());
    $this->assertArrayHasKey('users', $response->toArray());
}
```

### Bearer Authentication

[](#bearer-authentication)

```
$response = $client->withAuthBearer('your-token-here')->request('GET', '/api/admin');
```

### Access Cookies

[](#access-cookies)

```
$cookieJar = $client->kernelBrowser->getCookieJar();
$cookies = $cookieJar->all();
```

### Performance Optimization

[](#performance-optimization)

By default, Symfony reboots the kernel between requests. For better performance in tests with multiple requests:

```
$client = new TestHttpClient($kernelBrowser);
$client->kernelBrowser->disableReboot();

// Make multiple requests - kernel stays booted
$response1 = $client->request('GET', '/api/users');
$response2 = $client->request('GET', '/api/posts');
$response3 = $client->request('GET', '/api/comments');
```

Pest Expectations
-----------------

[](#pest-expectations)

If you're using Pest, the package includes custom expectations for testing responses:

```
use BenTools\TestHttpClient\TestHttpClient;

it('tests various response aspects', function () {
    $client = new TestHttpClient(static::createClient());
    $response = $client->request('GET', '/api/users');

    // Status code
    expect($response)->toHaveStatusCode(200);

    // Success (2xx)
    expect($response)->toBeSuccessful();

    // Client error (4xx)
    expect($response)->toBeClientError();

    // Server error (5xx)
    expect($response)->toBeServerError();

    // Headers
    expect($response)->toHaveHeader('content-type');
    expect($response)->toHaveHeader('cache-control', 'max-age=3600');

    // JSON
    expect($response)->toHaveJsonStructure();

    // JSON structure
    expect($response)->toHaveJsonStructure(['users', 'total', 'page']);
});
```

### Available Expectations

[](#available-expectations)

- `toHaveStatusCode(int $code)` - Assert status code
- `toBeSuccessful()` - Assert 2xx status
- `toBeClientError()` - Assert 4xx status
- `toBeServerError()` - Assert 5xx status
- `toHaveHeader(string $name, ?string $value = null)` - Assert header exists (optionally with value)
- `toHaveJsonStructure()` - Assert content-type is JSON
- `toHaveJsonStructure(array $keys)` - Assert JSON contains specific keys

Credits
-------

[](#credits)

Borrowed and adapted from Api-Platform's [TestClient](https://github.com/api-platform/core/blob/main/src/Symfony/Bundle/Test/Client.php).

License
-------

[](#license)

MIT.

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance81

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity46

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

Unknown

Total

1

Last Release

101d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/acdd1a8ee0e657ddd06cf11f98a32100ef7121afb8aa270a5b295f5c29c038b3?d=identicon)[bpolaszek](/maintainers/bpolaszek)

---

Top Contributors

[![bpolaszek](https://avatars.githubusercontent.com/u/5569077?v=4)](https://github.com/bpolaszek "bpolaszek (1 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/bentools-test-http-client/health.svg)

```
[![Health](https://phpackages.com/badges/bentools-test-http-client/health.svg)](https://phpackages.com/packages/bentools-test-http-client)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)

PHPackages © 2026

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