{"id":19308085,"url":"https://github.com/pgssoft/httpclientmock","last_synced_at":"2025-04-22T13:31:51.640Z","repository":{"id":49758473,"uuid":"173189708","full_name":"PGSSoft/HttpClientMock","owner":"PGSSoft","description":"Library for mocking Java 11 HttpClient.","archived":false,"fork":false,"pushed_at":"2023-08-08T21:07:20.000Z","size":177,"stargazers_count":21,"open_issues_count":2,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-02T00:11:19.524Z","etag":null,"topics":["httpclient","java","mock","test","unit-testing"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PGSSoft.png","metadata":{"files":{"readme":"README.MD","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-02-28T21:24:42.000Z","updated_at":"2024-10-17T14:08:14.000Z","dependencies_parsed_at":"2022-08-30T12:51:25.468Z","dependency_job_id":null,"html_url":"https://github.com/PGSSoft/HttpClientMock","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/PGSSoft%2FHttpClientMock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PGSSoft%2FHttpClientMock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PGSSoft%2FHttpClientMock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PGSSoft%2FHttpClientMock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PGSSoft","download_url":"https://codeload.github.com/PGSSoft/HttpClientMock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250248713,"owners_count":21399324,"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":["httpclient","java","mock","test","unit-testing"],"created_at":"2024-11-10T00:13:36.796Z","updated_at":"2025-04-22T13:31:51.320Z","avatar_url":"https://github.com/PGSSoft.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"![pgssoft-logo.png](pgssoft-logo.png)\n\n# HttpClientMock\n\nHttpClientMock is a library for mocking [Java HttpClient](https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html). It has an intuitive fluent API for defining client behaviour and verifing number of made requests.\n\n* [Installation](#installation)\n* [Requirements](#requirements)\n* [Usage](#usage)\n* [Request matching](#request-matching)\n* [Define response](#define-response)\n* [Verification](#verification)\n* [Examples](#examples)\n* [License](#license)\n* [About](#about)\n* [Follow us](#follow-us)\n\n## Installation\n\nHttpClientMock is available in Maven Central Repository.\n```\n\u003cdependency\u003e\n    \u003cgroupId\u003ecom.pgs-soft\u003c/groupId\u003e\n    \u003cartifactId\u003eHttpClientMock\u003c/artifactId\u003e\n    \u003cversion\u003e1.0.0\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\n## Requirements\n\n* Java 11\n\n## Usage\n\n#### Record\nWorking with HttpClientMock starts with defining client behaviour. Before code under tests starts HttpClientMock must know how to respond to every request.\n```\nHttpClientMock httpClientMock = new HttpClientMock();\nhttpClientMock.onGet(\"http://localhost/login\")\n  .withParameter(\"user\",\"john\")\n  .doReturn(\"Ok\");\nhttpClientMock.onPost(\"http://localhost/login\").doReturnStatus(501);\n```\n\n#### Replay\nCode under test starts and uses HttpClientMock with defined behaviour.\n```\nvar get = HttpRequest.newBuilder(URI.create(\"http://localhost/login?user:john\")).GET().build();\nvar post = HttpRequest.newBuilder(URI.create(\"http://localhost/login\")).POST(noBody()).build();\nhttpClient.send(get, ofString()); // returns response with body \"Ok\"\nhttpClient.send(post, ofString()); // returns response with status 501\n```\n\n#### Verify\nWhen code under test finishes, HttpClientMock allows to check number of made request. It is possible to use the same set of conditions as for defining mock behaviour.\n```\nhttpClientMock.verify().get(\"http://localhost/login\").withParameter(\"user\",\"john\").called()\nhttpClientMock.verify().post(\"http://localhost/login\").notCalled()\n```\n\n\n## Request matching\n\n### HTTP method\nHttpClientMock supports all Http methods.\n```\nhttpClientMock.onGet().doReturn(\"get\");\nhttpClientMock.onPost().doReturn(\"post\");\nhttpClientMock.onPut().doReturn(\"put\");\nhttpClientMock.onDelete().doReturn(\"delete\");\nhttpClientMock.onOptions().doReturn(\"options\");\nhttpClientMock.onHead().doReturn(\"head\");\n```\n### URL\nEvery `onGet()`, `onPost()`, .... method accept URL. It is possible to write:\n```\nhttpClientMock.onGet(\"http://localhost/login?user=john\").doReturnStatus(200);\n```\nwhich is equal to\n```\nhttpClientMock.onGet()\n  .withHost(\"httt://locahost\")\n  .withPath(\"/login\")\n  .withParameter(\"user\",\"john\")\n  .doReturnStatus(200);\n```\n\nIt is possible to define default host using HttpClientMock constructor, so later methods can accept relative URL-s.\n```\nHttpClientMock httpClientMock = new HttpClientMock(\"http://localhost\");\nhttpClientMock.onGet(\"/login\").doReturn(\"ok\");\nhttpClientMock.onPost(\"/edit?user=john\").doReturnStatus(200);\n\nhttpClientMock.onGet(\"http://www.google.com\").doReturn(\"Google\") // Absolute paths still work.\n```\n\n### Host, path, parameters, reference conditions\nIt is possible to define each part of url separately.\n```\nhttpClientMock.onGet()\n  .withHost(\"httt://locahost\")\n  .withPath(\"/login\")\n  .withParameter(\"user\",\"john\")\n  .withReference(\"edit\")\n  .doReturnStatus(200);\n```\n\n### Header condition\n```\nhttpClientMock.onGet(\"http://localhost/login\")\n  .withHeader(\"tracking\",\"123\")\n  .doReturn(\"ok\");\n```\n\n### Body condition\n```\nhttpClientMock.onGet(\"http://localhost/login\")\n  .withBody(\"tracking\",containsString(123))\n  .doReturn(\"ok\");\n```\n\n### Custom condition\n```\nCondition fooCondition = request -\u003e request.getUri().contains(\"foo\");\nhttpClientMock.onGet(\"http://localhost/foo/bar\")\n  .with(fooCondition)\n  .doReturn(\"yes\");\n```\n\n### Matchers\nEvery condition method accepts [Hamcrest Matcher](https://github.com/hamcrest/JavaHamcrest) which allows to define custom conditions on requests.\n```\nhttpClientMock.onGet(\"http://localhost\")\n  .withPath(containsString(\"login\"))\n  .withParameter(\"user\",equalToIgnoringCase(\"John)\")\n  .reference(not(equalTo(\"edit\")));\n```\n\n### Multiple matching rules\nIf request matches more then one rule, then last defined one is used.\n\n### None rule matche\nIf request doesn't matche any rule, HttpClientMock return response with status 404.\n\n## Define response\n\n### Response\nResponse with provided body and status 200.\n```\nhttpClientMock.onGet(\"http://localhost\").doReturn(\"my response\")\n```\n### Status\nResponse with empty body and provided status\n```\nhttpClientMock.onGet(\"http://localhost\").doReturnStatus(300)\nhttpClientMock.onGet(\"http://localhost\").doReturn(\"Overloaded\").withStatus(\"500\");\n```\n### Exception\nInstead of returning response it throws defined exception.\n```\nhttpClientMock.onGet(\"http://localhost\").doThrowException(new IOException());\n```\n### Custom action\n```\nAction echo r -\u003e {\n  HttpEntity entity = ((HttpEntityEnclosingRequestBase) r.getHttpRequest()).getEntity();\n  BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion(\"http\", 1, 1), 200, \"ok\");\n  response.setEntity(entity);\n  return response;\n};\nhttpClientMock.onGet(\"http://localhost\").doAction(echo);\n```\n### Response header\n```\nhttpClientMock.onPost(\"/login\").doReturn(\"foo\").withHeader(\"tracking\", \"123\")\n```\n### Response status\n```\nhttpClientMock.onPost(\"/login?user=bar\").doReturn(\"Wrong user\").withStatus(403)\n```\n\n### JSON\nResponse with provided body, status 200 and content type \"application/json\"\n```\nhttpClientMock.onPost(\"/login\").doReturnJSON(\"{foo:1}\");\n```\n\n### XML\nResponse with provided body, status 200 and content type \"application/xml\"\n```\nhttpClientMock.onPost(\"/login\").doReturnXML(\"\u003cfoo\u003ebar\u003c/foo\u003e\");\n```\n\n### Multiple actions\nIt is possible to add multiple actions to one rule. Every call will use next action until last is reached.\n```\nhttpClientMock.onPut(\"/addUser\")\n  .doReturn(\"ok\");\n  .doReturnStatus(500);\n\nvar req = HttpRequest.newBuilder(URI.create(\"http://localhost/addUser\")).PUT(noBody()).build();\nhttpClientMock.send(req, ofString()); //returns \"ok\"\nhttpClientMock.send(req, ofString()); //returns status 500\nhttpClientMock.send(req, ofString()); //returns status 500\n```\n\n\n## Verification\nHttpClientMock allows to check how many calls were made. Verification supports the same set of conditions us rule defining.\n```\nhttpClientMock.verify().get(\"http://localhost\").called();\n\nhttpClientMock.verify().get(\"http://localhost/login\")\n  .withParameter(\"user\",\"john\")\n  .called();\n\nhttpClientMock.verify().get(\"http://localhost/login\")\n  .withParameter(\"user\",\"Ben\")\n  .notCalled();\n\nhttpClientMock.verify().delete().notCalled();\n\nhttpClientMock.verify().get().called(greaterThanOrEqualTo(1));\n\n```\n# Examples\n## Example 1\n```\n// DEFINE BEHAVIOUR\nHttpClientMock httpClientMock = new HttpClientMock(\"http://localhost:8080\");\nhttpClientMock.onGet(\"/login?user=john\").doReturnJSON(\"{permission:1}\");\nhttpClientMock.onPost(\"/edit\")\n  .withParameter(\"user\",\"John\")\n  .doReturn(\"ok\")\n  .doReturnStatus(503);\n\n// EXECUTION\n// request to http://localhost:8080/login?user=john returns JSON {permission:1}\n// first request to http://localhost:8080/edit?user=john returns message \"ok\"\n// second request to http://localhost:8080/edit?user=john returns request with status 503\n\n// VERIFICATION\nhttpClientMock.verify().get(\"/login?user=john\").called();\nhttpClientMock.verify().post(\"/edit?user=john\").called(2);\nhttpClientMock.verify().delete().notCalled();\n```\n\n\n## Example 2\n```\n// DEFINE BEHAVIOUR\nHttpClientMock httpClientMock = new HttpClientMock();\nhttpClientMock.onGet(\"http://localhost:8080/login\").doReturn(\"Missing parameter user\").withStatus(400);\nhttpClientMock.onGet(\"http://localhost:8080/login\")\n  .withParameter(\"user\",\"JJohn\")\n  .doReturn(\"Wrong user name\").withStatus(403);\nhttpClientMock.onGet(\"http://localhost:8080/login\")\n  .withParameter(\"user\",\"John\")\n  .doReturn(\"ok\");\n\n// EXECUTION\n// request to http://localhost:8080/login?user=john returns message \"ok\"\n\n// VERIFICATION\nhttpClientMock.verify().get(\"/login?user=john\").called();\n```\n\n## License\n\nThe project is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n\n## About\n\nThe project maintained by [software development agency](https://www.pgs-soft.com/) [PGS Software](https://www.pgs-soft.com/).\nSee our other [open-source projects](https://github.com/PGSSoft) or [contact us](https://www.pgs-soft.com/contact-us/) to develop your product.\n\n## Follow us\n\n[![Twitter Follow](https://img.shields.io/twitter/follow/pgssoftware.svg?style=social\u0026label=Follow)](https://twitter.com/pgssoftware)\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpgssoft%2Fhttpclientmock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpgssoft%2Fhttpclientmock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpgssoft%2Fhttpclientmock/lists"}