mock_http_server library

An enterprise-grade, modern HTTP, HTTPS, and WebSocket mock server package designed for Dart and Flutter testing suites.

Classes

ApiKeyManager
Manages registered API Keys and enforces authorization scopes.
AuthMiddleware
A middleware that validates incoming requests. Halts the pipeline with a 401 Unauthorized response if validation fails.
CorsHandler
Pre-built CORS (Cross-Origin Resource Sharing) middleware handler.
DashboardHandler
Renders a highly interactive, gorgeous HSL glassmorphism console dashboard for inspecting live server states.
Dispatcher
An abstract interface representing a component that resolves a RecordedRequest into a MockResponse on the MockWebServer.
GraphQLDispatcher
A Dispatcher tailored specifically for intercepting and mocking GraphQL endpoints. Routes requests based on GraphQL operationName matching.
GraphQLRequest
Represents parsed metadata from a GraphQL request payload.
HarConverter
Exports and imports standard HAR (HTTP Archive v1.2) traffic profiles.
JsonSchemaValidator
Lightweight JSON Schema Validator verifying property existence and data types.
JwtValidator
Decodes and validates JWT (JSON Web Tokens) expiration and header formatting.
LoggingMiddleware
A middleware that prints incoming requests and outgoing responses with gorgeous ANSI colored console formats.
MetricsCollector
Diagnostics collector monitoring MockForge performance metrics.
MockFaker
A lightweight, zero-dependency mock fake-data generator for testing data bindings.
MockHttpServerChopperInterceptor
A custom Chopper RequestInterceptor that transparently intercepts requests and routes relative or loopback API calls to the active MockWebServer.
MockHttpServerDioAdapter
A custom Dio HttpClientAdapter that transparently intercepts requests and routes relative or loopback API calls to the active MockWebServer.
A custom GraphQL Link that transparently intercepts requests and routes all GraphQL client queries to the active MockWebServer.
MockHttpServerMiddleware
Base abstract class for defining server middlewares. Middlewares intercept incoming requests and outgoing responses, allowing modifications or short-circuiting the request pipeline.
MockResponse
Represents a configurable mock response returned by the MockWebServer. Uses a fluent builder pattern to configure responses easily.
MockRoute
Represents a single route mapping an HTTP method and path pattern to a handler.
MockWebServer
An enterprise-grade, modern HTTP/HTTPS mock server for Dart & Flutter.
MockWebSocketConnection
Represents an active mock WebSocket connection. Provides a broadcast stream of incoming frames, methods to transmit text/binary frames, and helper methods to configure message-triggered auto-replies.
OpenApiMockGenerator
Automatically maps OpenAPI 3.0 specifications to RouteDispatcher routes.
QueueDispatcher
A Dispatcher that resolves requests using a First-In-First-Out (FIFO) queue of MockResponses. Falls back to defaultResponse if the queue is empty.
RateLimiter
Implements a simple token-bucket rate limiter.
RecordedRequest
Immutable model representing an HTTP request captured by the MockWebServer.
RequestMatcher
Defines customizable, fluent rule sets to validate recorded client requests.
RouteDispatcher
A Dispatcher that routes HTTP requests to callback handlers based on HTTP methods and path matching templates or regular expressions.
SnapshotTester
Implements request snapshot validation testing to prevent regression changes.
SseEvent
Represents a single event frame emitted in a Server-Sent Events (SSE) connection stream.
SseResponseBuilder
Helper utility to construct a chunked, persistent MockResponse populated with a Server-Sent Events (SSE) stream.
TlsManager
Manages HTTPS / TLS configurations for MockWebServer. Provides mechanisms to build SecurityContext from PEM strings or files, and bundles a default self-signed certificate for easy localhost testing.
WebSocketHandler
Manages and routes WebSocket handshake upgrades for the MockWebServer.

Extensions

GraphQLRecordedRequestExtension on RecordedRequest
Extends RecordedRequest to provide easy access to GraphQL metadata.
PathParamsExtension on RecordedRequest
Extends RecordedRequest with route parameter parsing utilities.

Functions

expectJsonBody(RecordedRequest request, Map<String, dynamic> expectedJson) → void
Dynamic structural check validating matching key-values inside raw JSON payloads.
expectRequest(MockWebServer server, RequestMatcher matcher) Future<void>
Standard expectation helper checking if a recorded request matches specific rules. Throws a TestFailure if no matching request has been received.
waitForRequest(MockWebServer server, {Duration timeout = const Duration(seconds: 5)}) Future<RecordedRequest>
Blocks asynchronously until a request is received, or throws TimeoutException after the specified timeout window.

Typedefs

RouteHandler = FutureOr<MockResponse> Function(RecordedRequest request)
Callback handler type for a route in RouteDispatcher.
WebSocketConnectionHandler = void Function(MockWebSocketConnection connection)
Handler type invoked when a client successfully connects over WebSockets.

Exceptions / Errors

EmptyQueueException
Thrown when the mock response queue is empty and no default fallback response is configured.
MiddlewareResponseException
Thrown by middlewares to halt the request pipeline and return a custom response immediately.
MockHttpServerException
Custom exceptions thrown by the mock_http_server mock server.
ServerLifecycleException
Thrown when server lifecycle operations (start, stop, configure) fail.
TlsConfigurationException
Thrown when security certificate loading or TLS handshakes fail.
WebSocketMockException
Thrown when a WebSocket upgrade, connection, or framing error occurs.