HTTP Testing
pushinbr/pam-http-testing sends requests straight into your application’s pipeline, without opening a network
port. Routing, middleware, validation, resources, error handling and provider boot all run exactly as they do in
production, so tests are fast and deterministic.
(new TestClient($app)) ->get('/users/42') ->assertSuccessful() ->assertJsonPath('id', '42');The client works with any application that implements Pam\Contracts\Http\ApplicationInterface, including
Pam\App from pushinbr/pam-http.
Installation
Section titled “Installation”Add the package as a development dependency through PAM’s Composer:
pam composer require --dev pushinbr/pam-http-testingTests run inside PAM’s embedded PHP, so the runtime classes (Pam\Http\Request, Pam\Http\Response) are
available. Use pam test to run PHPUnit or Pest:
pam test --phpunit -c phpunit.xmlWriting Tests
Section titled “Writing Tests”Build the application in the test, without package discovery so the test controls every provider:
<?php
declare(strict_types=1);
use Pam\App;use Pam\Http\Request;use Pam\Http\Response;use Pam\Http\Testing\TestClient;use PHPUnit\Framework\TestCase;
final class UserApiTest extends TestCase{ public function testShowsAUser(): void { $app = new App(discoverPackages: false); $app->get('/users/{id}', static fn (Request $request, Response $response): Response => $response->json(['id' => $request->route('id'), 'notify' => $request->getQuery('notify')]));
(new TestClient($app)) ->get('/users/42?notify=1') ->assertSuccessful() ->assertHeader('content-type', 'application/json; charset=utf-8') ->assertJson(['id' => '42', 'notify' => '1']);
$this->addToAssertionCount(1); }}Assertions throw a RuntimeException when they fail, which PHPUnit reports as an error. Because they are not
PHPUnit assertions, add addToAssertionCount() (or a final assert* call) so PHPUnit does not flag the test as
risky.
Making Requests
Section titled “Making Requests”$client = new TestClient($app);
$client->get('/orders?status=1', ['authorization' => 'Bearer test-token']);
$client->postJson('/orders', ['sku' => 'ABC-1', 'quantity' => 2]);
$client->request( method: 'PATCH', target: '/orders/42', headers: ['content-type' => 'application/json', 'idempotency-key' => 'retry-1'], body: '{"quantity":3}',);targetmust be an absolute path. Its query string is parsed into the request.- Header names are lowercased; a header value can be a string or a list of strings.
postJson()encodes the payload withJSON_THROW_ON_ERROR, keeps Unicode unescaped and setscontent-type: application/json.- Every request gets a fresh
Pam\Http\Response, and the application’s request scope is opened and closed as in production.
Assertions
Section titled “Assertions”| Method | Passes when |
|---|---|
assertStatus(int $expected) |
The status equals $expected. |
assertSuccessful() |
The status is in the 2xx range. |
assertHeader(string $name, ?string $expected = null) |
The header exists and, when given, equals $expected. |
assertJson(array $expected) |
The decoded body is strictly equal to $expected (same keys, order and types). |
assertJsonPath(string $path, mixed $expected) |
The value at a dot-separated path, such as data.0.name, is strictly equal to $expected. |
Every assertion returns the response, so you can chain them.
Inspecting the Response
Section titled “Inspecting the Response”TestResponse exposes readonly status, headers (lowercased names, each a list of values), body and
chunks (for streamed responses), plus:
$response = $client->get('/api/products');
$response->header('content-type'); // values joined with ", ", or null$response->header('x-missing', 'default');$response->json(); // decoded body; throws JsonException on invalid JSONTesting Errors and Middleware
Section titled “Testing Errors and Middleware”Error responses go through the same boundary as in production:
$client->postJson('/api/products', ['name' => 10]) ->assertStatus(422) ->assertHeader('content-type', 'application/problem+json; charset=utf-8') ->assertJsonPath('code', 1);
$client->request('DELETE', '/api/ping') ->assertStatus(405) ->assertHeader('allow', 'GET, HEAD, OPTIONS');Testing With a Database
Section titled “Testing With a Database”Give each test its own SQLite file and run the migrations after boot():
private function application(): App{ $app = new App(discoverPackages: false); $app->provider(new ArcanoServiceProvider( new DatabaseConfig('default', [ 'default' => ['driver' => 'sqlite', 'database' => $this->database, 'prefix' => ''], ]), new ArcanoSchemaCompiler(dirname(__DIR__) . '/src/Models'), migrations: dirname(__DIR__) . '/database/migrations', )); $app->post('/api/products', [ProductController::class, 'store']); $app->boot();
$app->container()->get(ArcanoMigrationManager::class)->migrate();
return $app;}The starter application ships this test.
The Built-in Client
Section titled “The Built-in Client”pushinbr/pam-http also contains Pam\Api\Testing\TestClient, which accepts only Pam\App and has a slightly
different request() signature:
use Pam\Api\Testing\TestClient;
(new TestClient($app))->request('GET', '/users', query: ['page' => 2], headers: ['x-request-id' => 'abc']);Both clients offer get(), postJson() and the same assertions. Prefer Pam\Http\Testing\TestClient for new
tests: it works with any PAM application contract and parses query strings from the target.
What In-Memory Tests Cover
Section titled “What In-Memory Tests Cover”In-memory tests exercise routing and parameters, middleware order, the error boundary, request and response composition, provider boot and configuration freeze.
They do not open a socket, so they do not cover the HTTP parser, TLS, HTTP/2 or HTTP/3, listener limits, streaming
backpressure, timeouts, slow clients, client disconnects, worker supervision or WebSocket framing. Cover those by
running the application with pam dev or pam start and sending real requests.
API Reference
Section titled “API Reference”| Type | Members |
|---|---|
Pam\Http\Testing\TestClient |
__construct(ApplicationInterface $application); request(string $method, string $target, array $headers = [], string $body = ''); get(string $target, array $headers = []); postJson(string $target, array $payload, array $headers = []) |
Pam\Http\Testing\TestResponse |
Readonly status, headers, body, chunks; header(), json(), assertStatus(), assertSuccessful(), assertHeader(), assertJson(), assertJsonPath() |
pushinbr/pam-http-testing requires PHP 8.4 and pushinbr/pam-contracts ^1.0, and is licensed under the Apache
License 2.0.