{"id":16837733,"url":"https://github.com/orhanobut/mockwebserverplus","last_synced_at":"2025-03-17T04:33:20.847Z","repository":{"id":78683910,"uuid":"55151975","full_name":"orhanobut/mockwebserverplus","owner":"orhanobut","description":"✔️ OkHttp mockwebserver with fixtures extension","archived":false,"fork":false,"pushed_at":"2017-06-13T14:07:23.000Z","size":137,"stargazers_count":89,"open_issues_count":5,"forks_count":19,"subscribers_count":8,"default_branch":"master","last_synced_at":"2025-02-27T18:06:34.103Z","etag":null,"topics":["android","fixtures","mockwebserver","testing","testing-tools"],"latest_commit_sha":null,"homepage":"","language":"Java","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/orhanobut.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-03-31T13:16:44.000Z","updated_at":"2024-02-01T08:26:53.000Z","dependencies_parsed_at":"2023-07-19T14:30:24.612Z","dependency_job_id":null,"html_url":"https://github.com/orhanobut/mockwebserverplus","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/orhanobut%2Fmockwebserverplus","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orhanobut%2Fmockwebserverplus/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orhanobut%2Fmockwebserverplus/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/orhanobut%2Fmockwebserverplus/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/orhanobut","download_url":"https://codeload.github.com/orhanobut/mockwebserverplus/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243842052,"owners_count":20356596,"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":["android","fixtures","mockwebserver","testing","testing-tools"],"created_at":"2024-10-13T12:18:40.408Z","updated_at":"2025-03-17T04:33:20.841Z","avatar_url":"https://github.com/orhanobut.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"### mockwebserver +\n\n#### Issue\nMockWebServer is a great tool for mocking network requests/responses.\nIn order to add response, you need to set MockResponse body along with all\nproperties you need\n\n```java\n@Rule public MockWebServer server = new MockWebServer();\n\n@Test public void uglyTest() {\n  server.enqueue(new MockResponse()\n    .setStatusCode(200)\n    .setBody({\n               \"array\": [\n                 1,\n                 2,\n                 3\n               ],\n               \"boolean\": true,\n               \"null\": null,\n               \"number\": 123,\n               \"object\": {\n                 \"a\": \"b\",\n                 \"c\": \"d\",\n                 \"e\": \"f\"\n               },\n               \"string\": \"Hello World\"\n             })\n    .addHeader(\"HeaderKey:HeaderValue\")\n    .responseDelay(3, SECONDS)\n  );\n  \n  // execute request\n  // assert\n  // verify\n}\n```\n\nImagine it with huge json responses. It will obscure the method content and will be barely readable.\n\n\n#### Solution\nIn order to make it more readable, you can use fixtures. Move away your response to the fixtures and just reference them.\nMockWebServerPlus is a wrapper which contains MockWebServer with fixtures feature.\n\n##### Create a fixture yaml file under resources/fixtures\n\n```\nsrc\n├── test\n│   ├── java\n│   ├── resources\n│   │   ├── fixtures\n│   │   │   ├── foo_success.yaml\n│   │   │   ├── foo_failure.yaml\n```\n\n```yaml\nstatusCode : 200       // as the name says\ndelay: 0               // delays the response\nheaders:               // adds to the response\n- 'Auth:auth'\n- 'key:value'\nbody: 'common/body_file.json' // can be any path under /fixtures folder\n// or inline\nbody: \u003e                       // can be any text, json, plain etc. Use \u003e letter for scalar text\n    {\n      \"array\": [\n        1,\n        2,\n        3\n      ],\n      \"boolean\": true,\n      \"null\": null,\n      \"number\": 123,\n      \"object\": {\n        \"a\": \"b\",\n        \"c\": \"d\",\n        \"e\": \"f\"\n      },\n      \"string\": \"Hello World\"\n    }\n```\n\n### Use the file name to reference it. That's it!\n\n```java\n@Rule public MockWebServerPlus server = new MockWebServerPlus();\n\n@Test public void readableTest() {\n  server.enqueue(\"foo_success\");\n  \n  // execute request\n  // assert\n  // verify\n}\n```\n\n#### Use the generated Fixtures.java to reference your fixtures. Read the Generate Fixtures.java part\n```java\nserver.enqueue(Fixtures.FOO_SUCCESS);\n```\n\n### Enqueue multiple response\n```java\nserver.enqueue(Fixtures.FOO_SUCCESS, Fixtures.USER_REGISTER_SUCCESS);\n```\n\n### Custom Dispatcher\nYou may wish to use a custom dispatcher with the mock web server. \n\nFixtures can be used directly inside a Dispatcher:\n\n```\nnew Dispatcher() {\n  @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {\n    return Fixture.parseFrom(\"simple).toMockResponse();\n  }\n}\n```\n\n### Generate Fixtures.java\nYou can always use plain text to reference your fixtures.\n\n```java\nserver.enqueue(\"foo_success\");\n```\n\nbut you can also generate Fixtures.java file to have all of them with a task. This will make your code more type-safe.\nPut the following task into your build.gradle file and execute it when you add/modify your fixture resources.\n\n```groovy\ntask generateFixtures(dependsOn: copyTestResources) \u003c\u003c {\n  def directory = projectDir.path + '/src/test/java'\n  new File(directory + '/fixtures').mkdir()\n  def path = directory + \"/fixtures/Fixtures.java\"\n\n  def builder = '' \u003c\u003c ''\n  builder.append(\"package fixtures;\\n\\n\")\n  builder.append(\"public class Fixtures {\\n\\n\")\n  builder.append(\"  private Fixtures() {\\n\")\n  builder.append(\"    //no instance\\n\")\n  builder.append(\"  }\\n\\n\")\n\n  def resources = android.sourceSets.test.resources.srcDirs.getAt(0)\n  if (resources.size() \u003e 0) {\n    resources.eachDirMatch(\"fixtures\") { dir -\u003e\n      def fixturesFile = dir\n      fixturesFile.eachFile(FileType.FILES) { file -\u003e\n        if (file.name.endsWith(\".yaml\")) {\n          String fileName = file.name.split('\\\\.')[0]\n          builder.append(\"  public static final String \")\n              .append(fileName.toUpperCase())\n              .append(\" = \")\n              .append('\\\"')\n              .append(fileName)\n              .append('\\\";\\n')\n        }\n      }\n    }\n  }\n  builder.append(\"}\\n\")\n\n  new File(path).write(builder.toString())\n}\n\n```\n\nAbove solution will generate Fixtures.java when you execute it manually. But you might forget to execute it, you can\nmake it dependent for any task to make it automated. Whenever preBuild is executed, it will also execute this task\n\n```groovy\npreBuild.dependsOn generateFixtures\n```\n\n### Install\n```groovy\ntestCompile 'com.orhanobut:mockwebserverplus:2.0.0'\n\n// This is optional, but in order to be up-to-date with OkHttp changes, you can use the latest version\ntestCompile 'com.squareup.okhttp3:mockwebserver:3.7.0'  \n```\n\n#### Other proxy methods\n```java\nMockWebServerPlus.server()         // returns MockWebServer instance\nMockWebServerPlus.takeRequest()    // returns RecordedRequest\nMockWebServerPlus.url(String path) // returns url to execute\nMockWebServerPlus.setDispatcher(Dispatcher dispatcher)  // any custom dispatcher\nMockWebServerPlus.enqueue(SocketPolicy socketPolicy)    // Useful for network errors, such as DISCONNECT etc\n```\n\n### Get the fixture object\n```java\nFixture fixture = Fixture.parseFrom(Fixtures.SIMPLE);\n```\n\n### For non-android modules\nFor non-android modules, you may need to add the following tasks to copy your resources into classes dir\n```groovy\ntask copyTestResources(type: Copy) {\n  from sourceSets.test.resources\n  into sourceSets.test.output.classesDir\n}\n```\n\n### How it works\n\u003cimg src='https://github.com/orhanobut/mockwebserverplus/blob/master/art/how_it_works.png' width=600/\u003e\n\nAlso notice that accessing sourceSets should be without android.\n\n#### Credits\n[MockWebServer](https://github.com/square/okhttp/tree/master/mockwebserver) from Square\n\n### License\n\u003cpre\u003e\nCopyright 2017 Orhan Obut\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\u003c/pre\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Forhanobut%2Fmockwebserverplus","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Forhanobut%2Fmockwebserverplus","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Forhanobut%2Fmockwebserverplus/lists"}