VOOZH about

URL: https://deepwiki.com/hypervel/http-client/9-testing-and-mocking

⇱ Testing and Mocking | hypervel/http-client | DeepWiki


Loading...
Menu

Testing and Mocking

This document provides an overview of the HTTP client's built-in testing infrastructure. The testing system allows you to intercept HTTP requests in tests and return predefined responses without making real network calls. It consists of three integrated subsystems: stub callbacks for faking responses, response sequences for ordered responses, and request recording for assertions.

For detailed information on specific testing features, see:

Testing Architecture Overview

The testing system is built directly into the Factory class and operates through the middleware stack. When fake() is called, it activates three mechanisms: stub callbacks that match and respond to requests, a recording system that captures all request/response pairs, and optional strict mode that prevents unfaked requests from reaching the network.


Sources: src/Factory.php183-224 src/Factory.php289-306 src/Factory.php310-382

Core Testing Components

Factory Testing Methods

The Factory class provides the primary testing interface through several key methods:

MethodPurposeReturn Type
fake()Register stub callbacks to intercept requestsFactory
stubUrl()Stub a specific URL patternFactory
fakeSequence()Create a response sequence for a URL patternResponseSequence
sequence()Create a standalone response sequenceResponseSequence
response()Create a fake response for stubbingPromiseInterface
failedConnection()Create a simulated connection failureClosure
preventStrayRequests()Enable strict mode for unfaked requestsFactory
assertSent()Assert a request was sent matching criteriavoid
assertNotSent()Assert a request was not sentvoid
assertSentCount()Assert exact number of requests sentvoid
assertSentInOrder()Assert requests sent in specific ordervoid
assertSequencesAreEmpty()Assert all sequences are consumedvoid
assertNothingSent()Assert no requests were recordedvoid

Sources: src/Factory.php138-286 src/Factory.php310-382

ResponseSequence Class

The ResponseSequence class src/ResponseSequence.php12-132 manages ordered collections of responses. It provides methods to add responses and control behavior when the sequence is exhausted:

MethodPurpose
push()Add response with body, status, headers
pushStatus()Add response with only status code
pushFile()Add response from file contents
pushFailedConnection()Add connection failure
whenEmpty()Set fallback response when depleted
dontFailWhenEmpty()Return default 200 response when empty
isEmpty()Check if sequence has responses remaining

Sources: src/ResponseSequence.php37-132

How Stubbing Works in the Request Lifecycle

When fake() is called, the Factory stores stub callbacks in its stubCallbacks Collection src/Factory.php51 and enables recording src/Factory.php185 During request execution, createPendingRequest() src/Factory.php404-409 transfers these stub callbacks to the new PendingRequest instance, which builds them into the middleware stack as the first handler.


Sources: src/Factory.php183-224 src/Factory.php404-409 src/PendingRequest.php (inferred from middleware stack building)

The Recording System

When fake() is called, the Factory automatically begins recording all request/response pairs src/Factory.php289-306 Each time a request completes, the recordRequestResponsePair() method src/Factory.php301-306 appends a tuple of [Request, Response] to the recorded array src/Factory.php61

The recorded() method src/Factory.php387-399 provides filtered access to this array:


The recorded pairs are used by all assertion methods. When fake() is called, it resets the recorded array to empty src/Factory.php187 ensuring each test starts with a clean slate.

Sources: src/Factory.php54-61 src/Factory.php185-187 src/Factory.php289-306 src/Factory.php387-399

Preventing Stray Requests

The preventStrayRequests() method src/Factory.php265-270 enables strict mode where any request that doesn't match a registered stub will throw a RuntimeException. This flag is stored in $preventStrayRequests src/Factory.php71 and transferred to each PendingRequest via createPendingRequest() src/Factory.php407

StateBehavior
preventStrayRequests(true)Unfaked requests throw exception
preventStrayRequests(false) or allowStrayRequests()Unfaked requests proceed to network
Default after fake()false (stray requests allowed)

Sources: src/Factory.php69-78 src/Factory.php263-286 src/Factory.php407

Stub Callback Matching

Stub callbacks are stored in a Collection src/Factory.php51 and evaluated in order during request execution. The stubUrl() method src/Factory.php238-260 provides URL pattern matching using wildcard syntax:

PatternMatchesExample
*Any URLAll requests
example.com/*URLs starting with example.com/example.com/api/users
*/api/*URLs containing /api/https://example.com/api/v1

When a stub callback returns null, the next stub in the collection is tried src/Factory.php243 This allows multiple stubs with different patterns to coexist.

Sources: src/Factory.php50-52 src/Factory.php183-224 src/Factory.php238-260

Response Creation Methods

Factory::response()

The static response() method src/Factory.php141-155 creates a PromiseInterface wrapping a PSR-7 response:


Sources: src/Factory.php141-155

Factory::failedConnection()

The static failedConnection() method src/Factory.php160-170 creates a closure that returns a rejected promise with a ConnectException, simulating network failures:

Sources: src/Factory.php160-170

Integration with Request Lifecycle

The testing system integrates seamlessly with the standard request lifecycle. Fake responses flow through the same middleware stack (except the base HTTP handler), trigger the same events, and return the same Response objects as real requests. This ensures test code accurately reflects production behavior.


The stub handler is inserted at the beginning of the middleware stack in PendingRequest::buildHandlerStack(), ensuring it runs before any other handlers. The recorder handler is added after the stub handler to capture all completed requests, whether faked or real.

Sources: src/Factory.php404-409 src/PendingRequest.php (inferred from handler stack construction)

Basic Testing Workflow

A typical test follows this pattern:

  1. Setup: Call fake() to activate stubbing and recording
  2. Stub: Register responses using stubUrl(), fakeSequence(), or callback
  3. Execute: Make HTTP requests through the client
  4. Assert: Verify behavior using assertion methods

The detailed mechanics of each step are covered in the sub-pages: Faking Requests, Response Sequences, and Assertions.

Sources: src/Factory.php183-224 src/Factory.php238-260 src/Factory.php310-382

Stub Callbacks Collection Structure

The stubCallbacks property src/Factory.php51 uses a Collection from the hypervel/support package. Each call to fake() or stubUrl() merges new callbacks into this collection src/Factory.php202-221 The collection is transferred to each PendingRequest instance through the stub() method src/Factory.php407


When multiple stubs are registered, they are evaluated in the order they were added. The first stub that returns a non-null response handles the request.

Sources: src/Factory.php50-52 src/Factory.php183-224 src/Factory.php238-260 src/Factory.php404-409