mock_http_server 1.0.0
mock_http_server: ^1.0.0 copied to clipboard
A modern, enterprise-grade HTTP, HTTPS, and WebSocket mock server package for Dart and Flutter. Support queue-based matching, path/regex routing, middleware, delay/bandwidth simulation, GraphQL operat [...]
MockHttpServer #
Created and Maintained by Farhan Choksi
An enterprise-grade, modern HTTP, HTTPS, and WebSocket mock server package built for Dart 3 and Flutter. Inspired by Square's MockWebServer and mock_web_server, redesigned with robust modern Dart APIs, full null safety, extensible route dispatchers, middleware systems, and advanced network simulation utilities.
Key Features #
π HTTP Mock Server β Deploy loopback servers on static or random ports with IPv4 and IPv6 support. Expose hosts, ports, and dynamic URLs instantly.
π FIFO Queue & Defaults β Traditional First-In-First-Out response matching with configurable fallback responses.
π£οΈ Route-Based Dispatcher β Route HTTP requests using exact matches, path templates (/users/:id), regular expressions, and query filtering.
π HTTPS / TLS Support β Full HTTPS mock server support out of the box. Supply your own SecurityContext or utilize the pre-bundled self-signed testing certificate.
π WebSocket upgrades β Mock real-time full-duplex communication paths, monitor stream packets, and register automatic, rule-based message echos.
π Streaming & SSE (Server-Sent Events) β Simulate chunked downloads, long-lived streams, and HTML5 event source tickers with ease.
πΈοΈ GraphQL mocking β Automatic GraphQL operational extraction! Dispatch and match mocks based on operationName and queries.
π‘οΈ Chained Middleware β Stack filters before requests and after responses. Perform header additions, validate credentials, and halt requests.
π¨ Colored Logger β Pretty colored terminal logging to simplify local server debug sessions.
ποΈ Artificial Network Control β Add latency delays, throttle bandwidth (e.g. 56Kbps dial-up, slow 3G), or simulate instant TCP disconnects.
π― Modern Dart 3 β Full Dart 3 capabilities (sealed exceptions, extension-based path parameters, record structures) and 100% sound null safety.
Installation #
Add mock_http_server to your project's development dependencies:
dev_dependencies:
mock_http_server: ^1.0.0
And run:
dart pub get
Getting Started #
1. Traditional Queue-Based Mocking #
Perfect for unit tests where the request-response order is deterministic.
import 'package:http/http.dart' as http;
import 'package:mock_http_server/mock_http_server.dart';
import 'package:test/test.dart';
void main() async {
final server = MockWebServer();
await server.start(); // Dynamic port allocation
// Enqueue responses
server.enqueue(MockResponse().setStatusCode(200).setBody('{"hello": "world"}'));
server.enqueue(MockResponse().setStatusCode(404));
// Client requests
final response1 = await http.get(Uri.parse(server.url));
print(response1.body); // {"hello": "world"}
// Assert request details
final recorded = await server.takeRequest();
expect(recorded.path, '/');
expect(recorded.method, 'GET');
await server.shutdown();
}
2. Route & Path Dispatcher #
For routing requests dynamically based on paths, parameters, or methods.
import 'package:mock_http_server/mock_http_server.dart';
void main() async {
final server = MockWebServer();
final router = RouteDispatcher();
server.dispatcher = router;
// Exact Match
router.get('/api/v1/status', (request) {
return MockResponse().setStatusCode(200).setBody('{"healthy": true}');
});
// Path parameters segment extraction (/api/users/42)
router.get('/api/users/:id', (request) {
final params = request.pathParameters('/api/users/:id');
final userId = params['id'];
return MockResponse().setBody('{"user_id": "$userId"}');
});
// Regex paths matching
router.post(RegExp(r'/items/\d+'), (request) {
return MockResponse().setStatusCode(201).setBody('{"status": "created"}');
});
await server.start();
}
3. Middleware & Colored Logger #
Add logging and token-based protection to your local server.
final server = MockWebServer();
// Colored logs on every request/response transition
server.addMiddleware(const LoggingMiddleware(printHeaders: true));
// Force authorization headers checking
server.addMiddleware(AuthMiddleware.bearer('super-secret-token-xyz'));
4. Advanced Network Control #
Simulate bandwidth restrictions, delay start times, or abruptly terminate sockets.
// Introduce a 500ms delay and restrict download rate to 10 KB/s
final response = MockResponse()
.setStatusCode(200)
.setBody('A' * 100000)
.withDelay(Duration(milliseconds: 500))
.throttle(10240); // 10,240 bytes per second
// Simulate a sudden server disconnect
final disconnectResponse = MockResponse().disconnectClient();
5. WebSockets Upgrade & Echo Rules #
Configure WebSockets paths and establish automated reply triggers.
server.webSocketHandler.register('/ws/feed', (connection) {
// Transmit frame to client immediately on connection
connection.send('Stream opened');
// If client sends 'ping', auto respond with 'pong'
connection.addAutoReplyString('ping', 'pong');
// Stream listener
connection.stream.listen((message) {
print('WebSocket message: $message');
});
});
6. GraphQL Interceptor #
Extract operation names dynamically and serve mocked responses.
final gqlRouter = GraphQLDispatcher();
server.dispatcher = gqlRouter;
gqlRouter.query('FetchUserProfile', (request) {
final variables = request.graphQL?.variables;
return MockResponse().setBody('{"data": {"user": {"name": "Gulam"}}}');
});
7. Server-Sent Events (SSE) #
Expose streaming event tickers cleanly using SseResponseBuilder.
router.get('/api/ticks', (request) {
final controller = StreamController<SseEvent>();
// Emit ticking frames
controller.add(SseEvent(event: 'tick', data: 'One'));
controller.add(SseEvent(event: 'tick', data: 'Two'));
controller.close();
return SseResponseBuilder.build(controller.stream);
});
Verification & Tests #
To view complete verification coverage, explore the test/ directory.
Run package unit and integration tests locally:
dart test
Explore comprehensive usage examples in the example/ folder, which highlights full integrations inside Dio, standard http, widget tests (testWidgets), and full Flutter E2E integration test runs.
License #
MockHttpServer is licensed under the MIT License. See LICENSE for more information.