### Minimal Test Setup with MockWebServer Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md A basic setup for starting the mock server, configuring a single response, making a request, and cleaning up. ```dart final server = MockWebServer(); await server.start(); // Configure responses server.enqueue(httpCode: 200, body: '{}'); // Use server final response = await http.get(Uri.parse(server.url)); // Cleanup await server.shutdown(); ``` -------------------------------- ### start() Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Starts the mock web server, allowing it to listen for incoming HTTP connections on a specified or available port. ```APIDOC ## start() ### Description Starts the mock web server and begins listening for incoming HTTP connections. ### Method `Future start({int? port})` ### Parameters #### Path Parameters - **port** (`int?`) - Optional - The port number to listen on. If not specified, the OS assigns an available port. ### Return Type `Future` — Completes when the server is successfully started. ### Throws `SocketException` — If binding to the specified port fails (e.g., port already in use). ### Example ```dart final server = MockWebServer(); // Start on any available port await server.start(); // Or specify a port await server.start(port: 8080); ``` ``` -------------------------------- ### Basic Request/Response with MockWebServer Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Demonstrates setting up a mock server, enqueuing a response, making an HTTP GET request, and verifying the response and request details. Ensure the server is started before enqueuing responses and shut down afterwards. ```dart test('should send correct request and receive response', () async { final server = MockWebServer(); await server.start(); // Queue the expected response server.enqueue(httpCode: 200, body: '{"status": "ok"}'); // Make the request final response = await http.get(Uri.parse(server.url)); // Verify the response expect(response.statusCode, equals(200)); expect(response.body, equals('{"status": "ok"}')); // Verify the request final request = server.takeRequest(); expect(request.method, equals('GET')); await server.shutdown(); }); ``` -------------------------------- ### Start MockWebServer on an Available Port Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md Starts the MockWebServer and lets the operating system assign an available port. This is the recommended approach for testing to avoid port conflicts. The assigned port can be accessed via the `port` property after starting. ```dart // Let OS choose an available port (recommended for testing) await server.start(); print(server.port); // e.g., 52847 ``` -------------------------------- ### Create MockWebServer Instance Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Instantiate the MockWebServer class. The server is not started until start() is called. ```dart final server = MockWebServer(); ``` -------------------------------- ### Start Mock Server and Make Request (Dart) Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md Demonstrates how to start a mock web server, enqueue a response, make an HTTP request to it, and then shut down the server. Ensure the 'http' package is imported. ```dart import 'package:flutter_mock_web_server/flutter_mock_web_server.dart'; import 'package:http/http.dart' as http; void main() async { final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{"status": "ok"}'); final response = await http.get(Uri.parse(server.url)); print(response.body); await server.shutdown(); } ``` -------------------------------- ### Start MockWebServer and Get Port Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Starts the mock web server and retrieves the assigned port number. Useful for configuring HTTP clients to connect to the mock server. ```dart final server = MockWebServer(); await server.start(); print('Server listening on port: ${server.port}'); ``` -------------------------------- ### Start MockWebServer Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Starts the MockWebServer. Optionally specify a port. If no port is provided, the OS will assign an available port. ```dart final server = MockWebServer(); await server.start(); // Assigns an available port print('Server started on ${server.url}'); // Or specify a port: // await server.start(port: 8080); // print('Server started on ${server.url}'); ``` -------------------------------- ### Start and Shutdown MockWebServer Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md Use `start()` to initialize the server and begin listening for connections. Use `shutdown()` to close the server and clear its state. After `start()`, `server.port` and `server.url` are set, and queues are active. After `shutdown()`, `server.port` is -1, `server.url` is http://localhost:-1, queues are cleared, and the request stream stops receiving new events. ```dart final server = MockWebServer(); // Start: Initialize and begin listening for connections await server.start(); // Shutdown: Close server and clear all state await server.shutdown(); ``` -------------------------------- ### MockWebServer Constructor Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Creates a new instance of the mock web server. The server is not started until `start()` is called. ```APIDOC ## MockWebServer() ### Description Creates a new instance of the mock web server. No parameters required. The server is not started until `start()` is called. ### Constructor Signature ```dart MockWebServer() ``` ### Example ```dart final server = MockWebServer(); ``` ``` -------------------------------- ### Start MockWebServer on a Specific Port Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md Starts the MockWebServer and binds it to a specific port. Ensure the chosen port is not already in use, otherwise a `SocketException` will be thrown. ```dart // Bind to a specific port await server.start(port: 8080); ``` -------------------------------- ### Basic MockWebServer Usage Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/00_START_HERE.md This snippet demonstrates the fundamental workflow of using MockWebServer: creating an instance, starting the server, queuing a response, making a request, taking the request, verifying counts, and shutting down the server. Ensure the 'http' package is imported for making requests. ```dart import 'package:flutter_mock_web_server/flutter_mock_web_server.dart'; // Create instance final server = MockWebServer(); // Start server await server.start(); // or: await server.start(port: 8080); // Queue responses server.enqueue(httpCode: 200, body: '{"status": "ok"}'); // Make requests final response = await http.get(Uri.parse(server.url)); // Verify requests final request = server.takeRequest(); server.verifyRequestCount(1); server.verifyNoMoreRequests(); // Shutdown await server.shutdown(); ``` -------------------------------- ### Starting and Shutting Down the Mock Server with Future Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Represents asynchronous operations for starting and shutting down the mock server. Use await to ensure completion before proceeding. ```dart await server.start(); // Wait for server to start await server.shutdown(); // Wait for shutdown to complete ``` -------------------------------- ### Start MockWebServer Requesting Port 0 Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md Explicitly requests the operating system to assign an available port by passing `0` to the `start` method. This is functionally equivalent to not specifying a port or passing `null`. ```dart // Explicitly request port 0 (OS assignment) await server.start(port: 0); ``` -------------------------------- ### Configuration: Port Selection Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Explains how to select a specific port for the MockWebServer using the `start` method's `port` parameter. If omitted, an available port is automatically assigned. ```dart final server = MockWebServer(); await server.start(port: 8080); // Start on port 8080 print('Server URL: ${server.url}'); // e.g., http://localhost:8080 await server.shutdown(); // Example without specifying port: // await server.start(); // print('Server URL: ${server.url}'); // e.g., http://localhost:54321 ``` -------------------------------- ### MockWebServer Class Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md The main class for creating and managing a mock web server. Use this to define routes and start the server. ```dart MockWebServer { /// Creates a new MockWebServer. MockWebServer(); /// Starts the mock web server on a random available port. /// Returns the assigned port. Future start() async { // ... implementation details ... } /// Stops the mock web server. Future stop() async { // ... implementation details ... } /// Defines a route for a GET request. /// [path] is the URL path to match. /// [statusCode] is the HTTP status code to return. /// [body] is the response body. void enqueueGet(String path, {int statusCode = 200, String? body}) { // ... implementation details ... } /// Defines a route for a POST request. /// [path] is the URL path to match. /// [statusCode] is the HTTP status code to return. /// [body] is the response body. void enqueuePost(String path, {int statusCode = 200, String? body}) { // ... implementation details ... } /// Defines a route for any HTTP method. /// [path] is the URL path to match. /// [statusCode] is the HTTP status code to return. /// [body] is the response body. void enqueue(String method, String path, {int statusCode = 200, String? body}) { // ... implementation details ... } } ``` -------------------------------- ### Start Server and Make Network Request Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md Demonstrates the network-based operation mode where the server listens on a socket and standard HTTP clients make actual network calls. ```dart await server.start(); final response = await http.get(Uri.parse(server.url)); ``` -------------------------------- ### Multi-Response Scenario Setup Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md Enqueue multiple responses upfront to simulate a sequence of API calls. Each request will consume the next response in the order they were enqueued. ```dart final server = MockWebServer(); await server.start(); // Enqueue all expected responses upfront server.enqueue(httpCode: 201, body: '{"id": 1}', contentType: 'application/json'); server.enqueue(httpCode: 200, body: '{"id": 1, "name": "Updated"}', contentType: 'application/json'); server.enqueue(httpCode: 204, body: '', contentType: 'application/json'); server.enqueue(httpCode: 404, body: '{"error": "not found"}', contentType: 'application/json'); // Make requests in matching order // Each request consumes the next response ``` -------------------------------- ### Complete Test Template for API Client Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Demonstrates a full test lifecycle including setup, response queuing, request making, response verification, request inspection, and cleanup. ```dart import 'package:flutter_mock_web_server/flutter_mock_web_server.dart'; import 'package:http/http.dart' as http; import 'package:test/test.dart'; void main() { group('API Client Tests', () { late MockWebServer server; setUp(() async { server = MockWebServer(); await server.start(); }); tearDown(() async { await server.shutdown(); }); test('should create resource and return 201', () async { // 1. Queue response server.enqueue( httpCode: 201, body: '{"id": 42, "name": "Test"}', contentType: 'application/json', ); // 2. Make request final response = await http.post( Uri.parse(server.url), headers: {'Content-Type': 'application/json'}, body: '{"name": "Test"}', ); // 3. Verify response expect(response.statusCode, equals(201)); expect(response.body, contains('"id": 42')); // 4. Verify request final request = server.takeRequest(); expect(request.method, equals('POST')); // 5. Assert cleanup server.verifyNoMoreRequests(); }); }); } ``` -------------------------------- ### Fixed Port Configuration for Integration Tests Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md Configure the mock server to start on a specific port, useful for integration tests where URLs are hardcoded. ```dart final server = MockWebServer(); await server.start(port: 3000); // All clients can use http://localhost:3000 final response = await http.get(Uri.parse('http://localhost:3000/api')); ``` -------------------------------- ### Properly Shutdown MockWebServer Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Always ensure the `MockWebServer` is shut down to release resources. Using a `try-finally` block or `setUp`/`tearDown` in testing frameworks guarantees shutdown. ```dart // WRONG test('should work', () async { final server = MockWebServer(); await server.start(); // ... test code ... // Missing: await server.shutdown(); }); // RIGHT test('should work', () async { final server = MockWebServer(); await server.start(); try { // ... test code ... } finally { await server.shutdown(); } }); // BEST (with setUp/tearDown) setUp(() async { server = MockWebServer(); await server.start(); }); tearDown(() async { await server.shutdown(); }); ``` -------------------------------- ### port Property Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Returns the port number on which the server is listening. Returns -1 if the server has not been started or has been shut down. ```APIDOC ## port ### Description Returns the port number on which the server is listening. ### Type `int` ### Returns The port number, or `-1` if the server has not been started or has been shut down. ### Example ```dart final server = MockWebServer(); await server.start(); print('Server listening on port: ${server.port}'); ``` ``` -------------------------------- ### Get MockWebServer URL Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Retrieves the full URL of the running mock web server. This URL can be used to make HTTP requests to the mock server during tests. ```dart final server = MockWebServer(); await server.start(); final response = await http.get(Uri.parse(server.url)); ``` -------------------------------- ### Basic MockWebServer Usage Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/README.md Demonstrates the fundamental steps to set up and use MockWebServer for testing HTTP interactions. Ensure the 'mock_web_server' package is imported and an HTTP client is available. ```dart import 'package:mock_web_server/mock_web_server.dart'; import 'package:http/http.dart' as http; void main() async { var server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{"name": "John"}'); var response = await http.get(server.url); expect(response.statusCode, equals(200)); expect(response.body, equals('{"name": "John"}')); server.verifyRequestCount(1); server.verifyNoMoreRequests(); await server.shutdown(); } ``` -------------------------------- ### Instantiate MockWebServer Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/configuration.md MockWebServer is instantiated with a zero-argument constructor. All configuration is performed after instantiation. ```dart MockWebServer() ``` -------------------------------- ### Creating and Dispatching an http.Request Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Shows how to construct an http.Request, set its body, and dispatch it using the MockWebServer. This is useful for simulating client-side requests. ```dart server.enqueue(httpCode: 200, body: '{}'); final request = http.Request('POST', Uri.parse(server.url)); request.body = '{"key": "value"}'; final response = await server.dispatchRequest(request); ``` -------------------------------- ### Create a URI with Components Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Illustrates how to construct a URI object by specifying its individual components like scheme, host, port, path, and query parameters. ```dart final uri = Uri( scheme: 'http', host: 'localhost', port: 8080, path: '/api/users', queryParameters: {'id': '123'}, ); ``` -------------------------------- ### Directly Dispatch Request Without Socket Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Use `dispatchRequest()` for unit testing HTTP client logic in isolation when actual socket behavior is not required. This method bypasses the need to start or shut down the server and avoids socket overhead. ```dart test('should dispatch response directly', () async { server.enqueue(httpCode: 200, body: '{"result": "success"}'); final request = http.Request('GET', Uri.parse('http://example.com')); final response = await server.dispatchRequest(request); expect(response.statusCode, equals(200)); expect(response.body, contains('success')); expect(response.request, equals(request)); }); ``` -------------------------------- ### Create and Use an HTTP Response Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Demonstrates how to enqueue a mock HTTP response with a specific status code, body, and headers, and then make a request to retrieve it. ```dart server.enqueue(httpCode: 200, body: '{"status": "success"}'); final response = await http.get(Uri.parse(server.url)); print(response.statusCode); // 200 print(response.body); // {"status": "success"} print(response.headers); // {"content-type": "application/json"} ``` -------------------------------- ### Monitor All Requests with Stream Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md Illustrates how to use the `requestStream` to listen for and log all incoming requests, useful for debugging and verification. ```dart test('should monitor all requests', () async { final server = MockWebServer(); await server.start(); final requestLog = []; server.requestStream.listen((request) { requestLog.add('${request.method} ${request.url}'); }); server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse(server.url)); await http.post(Uri.parse(server.url)); await Future.delayed(Duration(milliseconds: 100)); expect(requestLog.length, equals(2)); expect(requestLog[0], contains('GET')); expect(requestLog[1], contains('POST')); await server.shutdown(); }); ``` -------------------------------- ### Monitoring Requests via Stream Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Demonstrates how to listen to a stream of incoming requests to the mock server. This is useful for observing request patterns or performing actions based on received requests, such as logging or dynamic response generation. A small delay might be needed to ensure the stream has processed all events. ```dart test('should monitor requests via stream', () async { final server = MockWebServer(); await server.start(); final receivedRequests = []; server.requestStream.listen((request) { receivedRequests.add(request); }); server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse(server.url)); await http.post(Uri.parse(server.url), body: '{"test": true}'); await Future.delayed(Duration(milliseconds: 100)); // Allow stream to process expect(receivedRequests.length, equals(2)); expect(receivedRequests[0].method, equals('GET')); expect(receivedRequests[1].method, equals('POST')); await server.shutdown(); }); ``` -------------------------------- ### Handle Multiple Requests Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md Demonstrates how to enqueue multiple responses and make corresponding requests, verifying that the correct number of requests were received. ```dart test('should handle multiple requests', () async { final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 201, body: '{"id": 1}'); server.enqueue(httpCode: 200, body: '{"id": 1, "name": "Updated"}'); server.enqueue(httpCode: 204, body: ''); await http.post(Uri.parse(server.url), body: '{"name": "Test"}'); await http.put(Uri.parse(server.url), body: '{"name": "Updated"}'); await http.delete(Uri.parse(server.url)); server.verifyRequestCount(3); server.verifyNoMoreRequests(); await server.shutdown(); }); ``` -------------------------------- ### url Property Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Returns the complete URL of the mock server as a string. Returns `http://localhost:-1` if the server is not running. ```APIDOC ## url ### Description Returns the complete URL of the mock server as a string. ### Type `String` ### Returns A string in the format `http://localhost:`. Returns `http://localhost:-1` if the server is not running. ### Example ```dart final server = MockWebServer(); await server.start(); final response = await http.get(Uri.parse(server.url)); ``` ``` -------------------------------- ### Create a QueueItem Instance Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/queue-item.md Instantiate a QueueItem with the desired HTTP status code, response body, and content type. ```dart final queueItem = QueueItem(200, '{"name": "John"}', 'application/json'); ``` -------------------------------- ### Verifying Request Headers Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Shows how to send requests with custom headers and then verify that the mock server received these headers correctly. Header keys are case-insensitive. ```dart test('should verify request headers', () async { final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{}'); await http.get( Uri.parse(server.url), headers: {'Authorization': 'Bearer token', 'X-Custom': 'value'}, ); final headers = server.takeRequestHeaders(); expect(headers['authorization']?.first, equals('Bearer token')); expect(headers['x-custom']?.first, equals('value')); await server.shutdown(); }); ``` -------------------------------- ### Basic Test: Fetch User Data Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md A fundamental test case demonstrating how to set up the mock server, enqueue a response, make a request, and verify the response. ```dart test('should fetch user data', () async { final server = MockWebServer(); await server.start(); server.enqueue( httpCode: 200, body: '{"id": 1, "name": "Alice"}', ); final response = await http.get(Uri.parse(server.url)); expect(response.statusCode, equals(200)); expect(response.body, contains('Alice')); await server.shutdown(); }); ``` -------------------------------- ### Verify Request Headers Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md Shows how to enqueue a response and then verify that specific headers, like 'Authorization', were sent with the request. ```dart test('should send authorization header', () async { final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{}'); await http.get( Uri.parse(server.url), headers: {'Authorization': 'Bearer token123'}, ); final headers = server.takeRequestHeaders(); expect(headers['authorization']?.first, equals('Bearer token123')); await server.shutdown(); }); ``` -------------------------------- ### Import Statement Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Import the flutter_mock_web_server package to use its functionalities. ```dart import 'package:flutter_mock_web_server/flutter_mock_web_server.dart'; ``` -------------------------------- ### enqueue() Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Adds a predefined HTTP response to a queue, which will be served to incoming requests in a First-In, First-Out (FIFO) order. ```APIDOC ## enqueue() ### Description Adds an HTTP response to the response queue. Responses are consumed in FIFO order as requests arrive. ### Method `void enqueue({required int httpCode, required String body, String? contentType})` ### Parameters #### Request Body - **httpCode** (`int`) - Required - HTTP status code (e.g., 200, 404, 500). - **body** (`String`) - Required - Response body as a string. Can be JSON, plain text, or any string content. - **contentType** (`String?`) - Optional - MIME type of the response body. Defaults to `'application/json'`. ### Return Type `void` — No return value. ### Example ```dart final server = MockWebServer(); await server.start(); // Enqueue a successful JSON response server.enqueue( httpCode: 200, body: '{"id": 1, "name": "John Doe"}', ); // Enqueue an error response server.enqueue( httpCode: 404, body: '{"error": "Not found"}', ); // Enqueue with custom content type server.enqueue( httpCode: 200, body: 'Hello', contentType: 'text/html', ); // Consume the responses var response1 = await http.get(Uri.parse(server.url)); var response2 = await http.get(Uri.parse(server.url)); var response3 = await http.get(Uri.parse(server.url)); ``` ``` -------------------------------- ### Usage Pattern: Direct Dispatch Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Demonstrates the direct dispatch pattern using `dispatchRequest`. This allows manually creating and sending a response for a given request without relying on the server's queue. ```dart test('direct dispatch pattern', () async { final request = http.Request('POST', server.url); request.body = 'Manual Request'; final response = http.Response('Directly Handled', 200); // Manually dispatch the response for the request await server.dispatchRequest(request, response); // Note: In this pattern, `takeRequest` might not behave as expected if the server // doesn't internally track dispatched requests in the same way as queued ones. // Verification might need to be handled differently based on the test setup. }); ``` -------------------------------- ### Log Incoming Requests with Stream Monitoring Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Listen to the request stream to log details of all incoming HTTP requests. This is useful for verifying that the correct requests are being sent to the mock server. ```dart test('should log all incoming requests', () async { final log = []; server.requestStream.listen((request) { log.add('${request.method} ${request.url.path}'); }); server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse('${server.url}/api/data')); await http.post(Uri.parse('${server.url}/api/data')); await Future.delayed(Duration(milliseconds: 100)); expect(log.length, equals(2)); expect(log[0], contains('GET')); expect(log[1], contains('POST')); }); ``` -------------------------------- ### MockWebServer API Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md The MockWebServer class provides methods to control and interact with a mock HTTP server for testing purposes. ```APIDOC ## MockWebServer ### `start()` #### Description Start the mock web server. Optionally specify a port to listen on. #### Signature `Future start({int? port})` ### `shutdown()` #### Description Stop the mock web server and clear any queued requests and responses. #### Signature `Future shutdown()` ### `enqueue()` #### Description Queue a mock response to be returned for subsequent requests. #### Parameters - **`httpCode`** (int) - Required - The HTTP status code for the response. - **`body`** (String) - Required - The response body. - **`contentType`** (String) - Optional - The content type of the response. #### Signature `void enqueue({required int httpCode, required String body, String? contentType})` ### `takeRequest()` #### Description Remove and return the next incoming HTTP request from the queue. #### Signature `http.Request takeRequest()` ### `takeRequestHeaders()` #### Description Remove and return the headers of the next incoming HTTP request from the queue. #### Signature `HttpHeaders takeRequestHeaders()` ### `verifyRequestCount()` #### Description Assert that the number of received requests exactly matches the specified count. #### Parameters - **`count`** (int) - Required - The expected number of requests. #### Signature `void verifyRequestCount(int count)` ### `verifyNoMoreRequests()` #### Description Assert that there are no more requests in the queue, meaning all expected requests have been received and processed. #### Signature `void verifyNoMoreRequests()` ### `dispatchRequest()` #### Description Manually dispatch a queued response for a given HTTP request. This is useful for more complex scenarios where you need to control which response is sent for a specific request. #### Parameters - **`request`** (http.Request) - Required - The incoming request to dispatch a response for. #### Returns `Future` - The HTTP response that was dispatched. #### Signature `Future dispatchRequest(http.Request request)` ## Properties ### `port` #### Description The port number the mock web server is currently listening on. #### Type `int` ### `url` #### Description The complete URL of the mock web server. #### Type `String` ### `requestStream` #### Description A stream of all incoming HTTP requests received by the mock web server. #### Type `Stream` ``` -------------------------------- ### Inspect Full Request Details Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Use `takeRequest()` to retrieve and inspect the full details of an incoming request, including method, URI, and headers. This consumes the request. ```dart test('verifies complete request details', () async { server.enqueue(httpCode: 200, body: '{}'); await http.post( Uri.parse('${server.url}/api/users'), body: '{"name": "Alice"}', ); final request = server.takeRequest(); expect(request.method, equals('POST')); expect(request.url.toString(), contains('/api/users')); }); ``` -------------------------------- ### Configuration: Default Content Type Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Details the default content type used by `MockWebServer.enqueue` when `contentType` is not explicitly provided. It defaults to 'application/json'. ```dart server.enqueue(httpCode: 200, body: '{"key": "value"}'); // contentType defaults to 'application/json' final request = await server.takeRequest(); // The Content-Type header in the response will be 'application/json' ``` -------------------------------- ### Common Test Pattern: Verifying No More Requests Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Illustrates how to use `verifyNoMoreRequests` to ensure that all expected requests have been made and no unexpected requests are pending. ```dart test('should not have remaining requests', () async { server.enqueue(httpCode: 200, body: 'OK'); await http.get(server.url); // If there were more enqueued responses or unhandled requests, this would fail. await server.verifyNoMoreRequests(); }); ``` -------------------------------- ### Handling Multiple Requests and Errors Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Illustrates how to queue multiple responses for sequential requests and handle different HTTP status codes. Use `verifyRequestCount` and `verifyNoMoreRequests` to ensure all expected requests were made and no unexpected ones occurred. ```dart test('should handle multiple requests with different responses', () async { final server = MockWebServer(); await server.start(); // Queue multiple responses server.enqueue(httpCode: 200, body: '{"data": "response1"}'); server.enqueue(httpCode: 404, body: '{"error": "not found"}'); server.enqueue(httpCode: 500, body: '{"error": "server error"}'); final response1 = await http.get(Uri.parse(server.url)); final response2 = await http.get(Uri.parse(server.url)); final response3 = await http.get(Uri.parse(server.url)); expect(response1.statusCode, equals(200)); expect(response2.statusCode, equals(404)); expect(response3.statusCode, equals(500)); server.verifyRequestCount(3); server.verifyNoMoreRequests(); await server.shutdown(); }); ``` -------------------------------- ### Monitor Incoming Requests with requestStream Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Listen to a stream of incoming HTTP requests made to the mock server. This is useful for verifying that the correct requests are being sent by the client under test. ```dart final server = MockWebServer(); await server.start(); server.requestStream.listen((request) { print('Received request: ${request.method} ${request.url}'); }); await http.get(Uri.parse(server.url)); ``` -------------------------------- ### shutdown() Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Closes the mock web server, releasing resources and clearing any queued requests or responses. ```APIDOC ## shutdown() ### Description Closes the server and clears all queued responses and requests. Must be called to clean up resources, typically in a test tearDown. ### Method `Future shutdown()` ### Return Type `Future` — Completes when the server is fully shut down. ### Example ```dart final server = MockWebServer(); await server.start(); // ... run tests ... await server.shutdown(); ``` ``` -------------------------------- ### Listening to Incoming HTTP Requests with Stream Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Subscribes to a broadcast stream that emits http.Request objects as they arrive at the mock server. Useful for inspecting requests in real-time. ```dart server.requestStream.listen((request) { print('Method: ${request.method}'); print('URL: ${request.url}'); }); ``` -------------------------------- ### Take a Request Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Takes the next incoming request from the queue. This method blocks until a request is received. ```dart final request = await server.takeRequest(); print('Received request: ${request.method} ${request.url}'); ``` -------------------------------- ### Common Test Pattern: Multiple Responses Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Demonstrates enqueuing multiple responses to handle a sequence of requests. Each request will receive the next response in the queue. ```dart test('should handle multiple responses', () async { server.enqueue(httpCode: 200, body: 'First'); server.enqueue(httpCode: 404, body: 'Not Found'); final response1 = await http.get(server.url); expect(response1.body, 'First'); final response2 = await http.get(server.url); expect(response2.statusCode, 404); expect(response2.body, 'Not Found'); await server.verifyRequestCount(2); }); ``` -------------------------------- ### Take a Request Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Retrieves and removes the next incoming HTTP request from the server's request queue. Requests are processed in FIFO order. This method is useful for asserting details about requests made to the mock server. ```dart final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{}'); await http.post( Uri.parse(server.url), body: '{"action": "create"}', ); final request = server.takeRequest(); expect(request.method, equals('POST')); expect(request.url.toString(), contains(server.url)); ``` -------------------------------- ### Handle Burst of Requests with Batch Enqueue Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md For performance, enqueue all expected responses upfront before making a large number of requests. This avoids overhead per request. ```dart test('should handle burst of requests', () async { // Enqueue all responses upfront for (int i = 0; i < 100; i++) { server.enqueue( httpCode: 200, body: '{"index": $i}', ); } // Make all requests final futures = []; for (int i = 0; i < 100; i++) { futures.add(http.get(Uri.parse(server.url))); } await Future.wait(futures); server.verifyRequestCount(100); }); ``` -------------------------------- ### Common Test Pattern: Response with JSON Body Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Demonstrates how to enqueue a response with a JSON body and the appropriate content type. ```dart test('should respond with JSON', () async { final jsonBody = '{"message": "Hello"}'; server.enqueue( httpCode: 200, body: jsonBody, contentType: 'application/json', ); final response = await http.get(server.url); expect(response.statusCode, 200); expect(response.headers['content-type'], contains('application/json')); expect(response.body, jsonBody); }); ``` -------------------------------- ### Combine Verification Methods Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md This pattern demonstrates how to combine multiple verification methods, such as checking the request count and inspecting individual request details like the HTTP method. ```dart test('should verify request details and count', () async { server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse('${server.url}/api/users')); await http.post(Uri.parse('${server.url}/api/users'), body: '{"name": "Alice"}'); // Verify count server.verifyRequestCount(2); // Verify details final req1 = server.takeRequest(); expect(req1.method, equals('GET')); final req2 = server.takeRequest(); expect(req2.method, equals('POST')); // Verify no more server.verifyNoMoreRequests(); }); ``` -------------------------------- ### Handle Server Errors with Different HTTP Codes Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/README.md Demonstrates how to enqueue responses with various HTTP error codes (400, 401, 500) and verify that the client receives these error statuses. ```dart test('should handle server errors', () async { final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 400, body: '{"error": "bad request"}'); server.enqueue(httpCode: 401, body: '{"error": "unauthorized"}'); server.enqueue(httpCode: 500, body: '{"error": "internal error"}'); final resp400 = await http.get(Uri.parse(server.url)); final resp401 = await http.get(Uri.parse(server.url)); final resp500 = await http.get(Uri.parse(server.url)); expect(resp400.statusCode, equals(400)); expect(resp401.statusCode, equals(401)); expect(resp500.statusCode, equals(500)); await server.shutdown(); }); ``` -------------------------------- ### Common Test Pattern: Basic Request/Response Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md A fundamental test pattern demonstrating how to enqueue a response and then verify that a request was received. ```dart test('should respond with success', () async { server.enqueue(httpCode: 200, body: 'Success!'); final response = await http.get(server.url); expect(response.statusCode, 200); expect(response.body, 'Success!'); final request = await server.takeRequest(); expect(request.method, 'GET'); }); ``` -------------------------------- ### Error: No request header received Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md This error indicates that the MockWebServer did not receive any request headers, which can happen due to network issues or improperly formed requests. ```dart // This error is typically due to client-side issues or network interruptions. // Ensure the client is correctly sending HTTP requests. ``` -------------------------------- ### Accessing HttpHeaders Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Demonstrates how to retrieve and access specific headers from a request. Header names are case-insensitive, and values are lists of strings. ```dart final headers = server.takeRequestHeaders(); final userAgent = headers['user-agent']?.first; final authorization = headers['authorization']?.first; ``` -------------------------------- ### Common Mistake: Not Verifying Requests Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Illustrates the mistake of not verifying that all expected requests were made, potentially leaving unhandled requests or masking issues. ```dart test('WRONG: not verifying requests', () async { server.enqueue(httpCode: 200, body: 'First'); server.enqueue(httpCode: 200, body: 'Second'); await http.get(server.url); // Only one request is made // Missing verification: If the test expects two requests, this is a mistake. // await server.verifyRequestCount(2); // This would fail if uncommented // await server.verifyNoMoreRequests(); // This would also fail if uncommented // RIGHT way: await server.verifyRequestCount(1); await server.verifyNoMoreRequests(); }); ``` -------------------------------- ### Error: Request received, but no response queued Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md This error occurs when a request is received by the MockWebServer, but there are no responses available in the queue to serve. ```dart // Ensure you enqueue a response before making a request: // server.enqueue(httpCode: 200, body: 'OK'); // final response = await http.get(server.url); // This scenario would trigger the error if enqueue was missed. ``` -------------------------------- ### Parse a URI from a String Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Shows how to parse a Uniform Resource Identifier (URI) from a string representation. ```dart final uri = Uri.parse('http://localhost:8080/api/users'); ``` -------------------------------- ### Enqueueing a Response with Map Headers Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Enqueues a mock HTTP response. Response headers are standard Dart Map. ```dart server.enqueue( httpCode: 200, body: '{"name": "John"}', contentType: 'application/json', ); // Response headers are accessible as Map final response = await http.get(Uri.parse(server.url)); print(response.headers['content-type']); // application/json ``` -------------------------------- ### Match Enqueue Order with Request Order Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Ensure the order in which responses are enqueued matches the order in which requests are made. Mismatched order leads to unexpected responses being returned. ```dart // WRONG server.enqueue(httpCode: 200, body: 'response1'); server.enqueue(httpCode: 404, body: 'response2'); await http.get(Uri.parse(server.url)); // Gets response1 await http.get(Uri.parse(server.url)); // Gets response2 (but expected response1) // RIGHT server.enqueue(httpCode: 200, body: 'response1'); server.enqueue(httpCode: 200, body: 'response2'); await http.get(Uri.parse(server.url)); await http.get(Uri.parse(server.url)); ``` -------------------------------- ### Mock Binary/Custom Response Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Enqueue a mock HTTP response with binary or custom content, using 'application/octet-stream' as the content type. ```dart server.enqueue( httpCode: 200, body: 'base64-encoded-or-other-content', contentType: 'application/octet-stream', ); ``` -------------------------------- ### Usage Pattern: Error Handling Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Illustrates a pattern for catching and handling potential errors that may arise during server operations or request processing. ```dart test('error handling pattern', () async { try { // Simulate an error condition, e.g., taking a request when none is available await server.takeRequest(); } catch (e) { print('Caught expected error: $e'); // Handle the error appropriately, e.g., assert specific error types or messages expect(e, isA()); } }); ``` -------------------------------- ### verifyRequestCount() Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Validates that the mock server has received an exact number of HTTP requests, throwing an error if the count does not match. ```APIDOC ## verifyRequestCount() ### Description Verifies that exactly the specified number of HTTP requests have been received by the server. ### Method `void verifyRequestCount(int count)` ### Parameters #### Path Parameters - **count** (`int`) - Required - The expected number of requests. ### Return Type `void` — No return value. ### Throws `StateError` — If the actual request count does not match the expected count. ### Example ```dart final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse(server.url)); await http.post(Uri.parse(server.url)); await http.put(Uri.parse(server.url)); // Verify exactly 3 requests were received server.verifyRequestCount(3); // This would throw: // server.verifyRequestCount(2); // StateError: Expected 2 requests, but received 3 ``` ``` -------------------------------- ### Catching MockWebServer StateErrors Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/errors.md All errors from MockWebServer are instances of `StateError`. This pattern shows how to catch these errors consistently and access their messages for handling. ```dart try { final request = server.takeRequest(); } on StateError catch (e) { print('MockWebServer error: ${e.message}'); // Handle error appropriately } ``` -------------------------------- ### Verify Large Request Batches Efficiently Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Efficiently verify a large number of incoming requests using `verifyRequestCount` and `verifyNoMoreRequests` instead of individually taking each request. ```dart test('should verify many requests efficiently', () async { const count = 100; // Queue responses for (int i = 0; i < count; i++) { server.enqueue(httpCode: 200, body: '{}'); } // Make requests for (int i = 0; i < count; i++) { await http.get(Uri.parse(server.url)); } // Verify count is more efficient than individual takeRequest() server.verifyRequestCount(count); server.verifyNoMoreRequests(); }); ``` -------------------------------- ### Verify No Extra Requests Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md This pattern ensures that no unexpected or additional requests were made beyond those explicitly handled. It's crucial for preventing unintended side effects. ```dart test('should verify no unexpected requests', () async { server.enqueue(httpCode: 200, body: '{}'); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse(server.url)); await http.post(Uri.parse(server.url)); // Consume all expected requests server.takeRequest(); server.takeRequest(); // Verify no requests remain (common assertion at test end) server.verifyNoMoreRequests(); }); ``` -------------------------------- ### QueueItem Constructor Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Internal data class constructor for QueueItem. Represents a queued response with HTTP status code, body, and content type. ```dart final queueItem = QueueItem(200, 'Success', 'application/json'); ``` -------------------------------- ### Common Test Pattern: Request Headers Inspection Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/INDEX.md Shows how to inspect the headers of an incoming request. This is useful for verifying that the client is sending the correct headers. ```dart test('should receive correct headers', () async { server.enqueue(httpCode: 200, body: 'OK'); await http.get(server.url, headers: {'X-Custom-Header': 'test'}); final request = await server.takeRequest(); expect(request.headers['X-Custom-Header'], 'test'); }); ``` -------------------------------- ### takeRequest() Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Retrieves and removes the next incoming HTTP request from the queue, allowing for inspection of request details. ```APIDOC ## takeRequest() ### Description Removes and returns the next HTTP request from the request queue. Requests are consumed in FIFO order. ### Method `http.Request takeRequest()` ### Return Type `http.Request` — The next request in the queue. ### Throws `StateError` — If no requests have been received. ### Example ```dart final server = MockWebServer(); await server.start(); server.enqueue(httpCode: 200, body: '{}'); await http.post( Uri.parse(server.url), body: '{"action": "create"}', ); final request = server.takeRequest(); expect(request.method, equals('POST')); expect(request.url.toString(), contains(server.url)); ``` ``` -------------------------------- ### Enqueue Responses Before Making Requests Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Always enqueue responses before making HTTP requests to avoid a `StateError: no response queued`. This ensures the mock server has a response ready for each outgoing request. ```dart // WRONG server.start(); await http.get(Uri.parse(server.url)); // StateError: no response queued // RIGHT server.start(); server.enqueue(httpCode: 200, body: '{}'); await http.get(Uri.parse(server.url)); ``` -------------------------------- ### Dispatching a Request Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/types.md Represents an asynchronous HTTP response operation. Used as the return type for `MockWebServer.dispatchRequest()`. ```dart final response = await server.dispatchRequest(request); ``` -------------------------------- ### Enqueue Mock Responses Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/api-reference/mock-web-server.md Adds predefined HTTP responses to a queue for the mock server to serve. Responses are processed in a First-In, First-Out (FIFO) order. You can specify the HTTP status code, response body, and content type. The default content type is 'application/json'. ```dart final server = MockWebServer(); await server.start(); // Enqueue a successful JSON response server.enqueue( httpCode: 200, body: '{"id": 1, "name": "John Doe"}', ); // Enqueue an error response server.enqueue( httpCode: 404, body: '{"error": "Not found"}', ); // Enqueue with custom content type server.enqueue( httpCode: 200, body: 'Hello', contentType: 'text/html', ); // Consume the responses var response1 = await http.get(Uri.parse(server.url)); var response2 = await http.get(Uri.parse(server.url)); var response3 = await http.get(Uri.parse(server.url)); ``` -------------------------------- ### Mock XML Response Source: https://github.com/jandrop/flutter_mock_web_server/blob/main/_autodocs/usage-patterns.md Enqueue a mock HTTP response with XML content, specifying the 'application/xml' content type. ```dart server.enqueue( httpCode: 200, body: 'value', contentType: 'application/xml', ); ```