{"id":17158950,"url":"https://github.com/trevorwang/mock-web-server","last_synced_at":"2025-03-24T14:43:17.302Z","repository":{"id":70694108,"uuid":"197717806","full_name":"trevorwang/mock-web-server","owner":"trevorwang","description":"mirror of MockWebServer","archived":false,"fork":false,"pushed_at":"2019-07-19T06:47:53.000Z","size":33,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-01-29T19:31:09.191Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://git.starcarr.co/Dart/MockWebServer","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/trevorwang.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-07-19T06:47:36.000Z","updated_at":"2023-10-10T04:32:13.000Z","dependencies_parsed_at":null,"dependency_job_id":"f2783486-b345-4956-8b95-01a4e1093eec","html_url":"https://github.com/trevorwang/mock-web-server","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trevorwang%2Fmock-web-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trevorwang%2Fmock-web-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trevorwang%2Fmock-web-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/trevorwang%2Fmock-web-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/trevorwang","download_url":"https://codeload.github.com/trevorwang/mock-web-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245294498,"owners_count":20591898,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-14T22:12:56.060Z","updated_at":"2025-03-24T14:43:17.296Z","avatar_url":"https://github.com/trevorwang.png","language":"Dart","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MockWebServer\n![build status](https://gitlab.com/Starcarr/MockWebServer/badges/master/build.svg)\n\nA flexible Dart web server that can be used to script tests and web server interactions\n\n## Summary\n\nThe best way to do integration tests, or to reproduce specific edge cases, is to\nbe able to script the interaction between the software that is being tested and the\nweb server.\n\nMockWebServer aims to facility testing by offering a flexible stand alone\nServer that will respond with a given script (or forward the request to your dispatcher).\n\nMockWebServer is based on the \n[library](https://github.com/square/okhttp/tree/master/mockwebserver) \nof the same name created by Square for Java.\n\n## Usage\n\n### Starting it\nMockWebServer can run in a given port or an ephemeral one\n```dart\nnew MockWebServer(); // Will use an ephemeral port picked by the system\nnew MockWebServer(port: 8081); // Will use 8081\n```\n\nTo start it just do\n```dart\nMockWebServer server = new MockWebServer();\nserver.start();\n```\n\nOnce you have the server running you will want to get the url of it, so that you can\nconfigure your app to connect there\n\n```dart\nserver.url; // will return http://127.0.0.1:8081\nserver.port; // 8081\nserver.host; // 127.0.0.1\n```\n\n### Adding responses to the queue\nOnce the server is started, you can queue the responses that you want. **The response queue is \nFirst In First Out**\n\n```dart\n// Enqueue an empty body with response code 401\nserver.enqueue(httpCode: 401);\n\n// Response code defaults to 200, so this will be a 200 with the given json as the body\nserver.enqueue(body: '{ \"message\" : \"hi\"}');\n\n// HTTP 200 with empty body and some header\nMap\u003cString, String\u003e headers = new Map();\nheaders[\"X-Server\"] = \"MockDart\";\nserver.enqueue(headers: headers);\n\n// All the parameters are optional so you can mix and match according to what you need\nserver.enqueue(httpCode: 201, body: \"answer\", headers: headers, duration: duration);\n\n// You can always call enqueueResponse() to directly enqueue a MockResponse\nMap\u003cString, String\u003e headers = new Map();\nheaders[\"X-Server\"] = \"MockDart\";\n\nvar mockResponse = new MockResponse()\n  ..httpCode = 201\n  ..body = \"Created\"\n  ..headers = headers\n  ..delay = new Duration(seconds: 2);\n\nserver.enqueueResponse(mockResponse);\n```\n\n### Delaying the response\nTo test timeouts or race conditions you may want to have the server take some time\n\n```dart\nserver.enqueue(delay: new Duration(seconds: 2), httpCode: 201);\nStopwatch stopwatch = new Stopwatch();\nstopwatch.start();\n\nHttpClientResponse response = request(path: \"\");\n\nstopwatch.stop();\nexpect(stopwatch.elapsed.inMilliseconds, greaterThanOrEqualTo(2000));\nexpect(response.statusCode, 201);\n```\n\n### Validating that the request was correct\nYou may want to check that your app is sending the correct requests. To do so you can obtain the\nrequests that have been made to the server. **The request queue is Last In First Out**\n\n```dart\nserver.enqueue(body: \"a\");\nserver.enqueue(body: \"b\");\nserver.enqueue(body: \"c\");\n\nrequest(path: \"first\");\nrequest(path: \"second\");\nrequest(path: \"third\");\n\n// takeRequest is FIFO\n// You should probably assign takeRequest() to a var so that you can \n// validate multiple things.\nexpect(server.takeRequest().headers['x-header'], \"nosniff\");\nexpect(server.takeRequest().method, \"GET\");\nexpect(server.takeRequest().uri.path, \"/third\");\n```\n\n### Using a dispatcher for fine-grained routing\n\nIf you want more control than what the FIFO queue offers, you can set a dispatcher and set \nthe logic there.\n\n```dart\nvar dispatcher = (HttpRequest request) {\n  if (request.uri.path == \"/users\") {\n    return new MockResponse()\n      ..httpCode = 200\n      ..body = \"working\";\n  } else if (request.uri.path == \"/users/1\") {\n    return new MockResponse()..httpCode = 201;\n  }\n\n  return new MockResponse()..httpCode = 404;\n};\n\nserver.dispatcher = dispatcher;\n\nHttpClientResponse response = request(path: \"unknown\");\nexpect(response.statusCode, 404);\n\nresponse = request(path: \"users\");\nexpect(response.statusCode, 200);\nexpect(read(response), \"working\");\n\nresponse = request(path: \"users/1\");\nexpect(response.statusCode, 201);\n```\n\n### TLS\nYou can start the server using TLS by passing the `certificate` parameter \nwhen creating the instance of MockWebServer. For example using the included certificates and the\n`resource` library you would do\n\n```dart\nvar chainRes =\n    new Resource('package:mock_web_server/certificates/server_chain.pem');\nList\u003cint\u003e chain = await chainRes.readAsBytes();\n\nvar keyRes =\n    new Resource('package:mock_web_server/certificates/server_key.pem');\nList\u003cint\u003e key = await keyRes.readAsBytes();\n\nCertificate certificate = new Certificate()\n  ..password = \"dartdart\"\n  ..key = key\n  ..chain = chain;\n\nMockWebServer _server =\n    new MockWebServer(certificate: certificate);\n```\n\nIf you do so, and your client validates the certs, you will need to use a\nproper `SecurityContext`, for example using the included `trusted_certs.pem`\n\n```dart\nvar certRes =\n    new Resource('package:mock_web_server/certificates/trusted_certs.pem');\nList\u003cint\u003e cert = await certRes.readAsBytes();\n\nSecurityContext clientContext = new SecurityContext()\n   ..setTrustedCertificatesBytes(cert);\n    \nvar client = new HttpClient(context: clientContext);\n\n```  \n\nPlease check the tests of MockWebServer to see a complete example of this.\n\n### IPv6\nIf want to use IPv6, you can pass `addressType: InternetAddressType.IP_V6` in the \nconstructor to have the server use it. Keep in mind that the `host` property \nwill then be `::1` instead of `127.0.0.1`.  \n\n```dart\nMockWebServer _server =\n        new MockWebServer(port: 8030, addressType: InternetAddressType.IP_V6);\n\n```\n\n### Stopping\nDuring the `tearDown` of your tests you should stop the server. `server.shutdown()` will do.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrevorwang%2Fmock-web-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftrevorwang%2Fmock-web-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftrevorwang%2Fmock-web-server/lists"}