{"id":3564,"url":"https://github.com/andrzejchm/RESTMock","last_synced_at":"2025-08-03T20:32:38.046Z","repository":{"id":40693818,"uuid":"56791509","full_name":"andrzejchm/RESTMock","owner":"andrzejchm","description":"HTTP Server for Android Instrumentation tests","archived":false,"fork":false,"pushed_at":"2022-07-14T11:51:07.000Z","size":337,"stargazers_count":756,"open_issues_count":5,"forks_count":58,"subscribers_count":19,"default_branch":"master","last_synced_at":"2024-12-07T02:26:51.352Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://medium.com/@andrzejchm/ittd-instrumentation-ttd-for-android-4894cbb82d37#.uir3loxu7","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/andrzejchm.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":"2016-04-21T17:01:46.000Z","updated_at":"2024-11-02T04:46:23.000Z","dependencies_parsed_at":"2022-09-07T10:53:18.426Z","dependency_job_id":null,"html_url":"https://github.com/andrzejchm/RESTMock","commit_stats":null,"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrzejchm%2FRESTMock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrzejchm%2FRESTMock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrzejchm%2FRESTMock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andrzejchm%2FRESTMock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andrzejchm","download_url":"https://codeload.github.com/andrzejchm/RESTMock/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":228567009,"owners_count":17937983,"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-01-05T20:16:45.074Z","updated_at":"2024-12-07T05:30:40.095Z","avatar_url":"https://github.com/andrzejchm.png","language":"Java","funding_links":[],"categories":["Test","Libraries","测试"],"sub_categories":["Networking"],"readme":"\n# RESTMock\n[![](https://jitpack.io/v/andrzejchm/RESTMock.svg)](https://jitpack.io/#andrzejchm/RESTMock)\n[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-RESTMock-green.svg?style=true)](https://android-arsenal.com/details/1/3468) [![Circle CI](https://circleci.com/gh/andrzejchm/RESTMock.svg?style=svg)](https://circleci.com/gh/andrzejchm/RESTMock)\n\nREST API mocking made easy.\n\nRESTMock is a library working on top of Square's [okhttp/MockWebServer](https://github.com/square/okhttp/tree/master/mockwebserver). It allows you to specify [Hamcrest](https://github.com/hamcrest/JavaHamcrest) matchers to match HTTP requests and specify what response to return. It is as easy as:\n\n\n```java\nRESTMockServer.whenGET(pathContains(\"users/andrzejchm\"))\n            .thenReturnFile(200, \"users/andrzejchm.json\");\n```\n**Article**\n- [ITDD - Instrumentation TDD for Android](https://medium.com/@andrzejchm/ittd-instrumentation-ttd-for-android-4894cbb82d37)\n\n## Table of contents\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\n\u003c!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --\u003e\n\n\n- [Setup](#setup)\n    - [Step 1: Repository](#step-1-repository)\n    - [Step 2: Dependencies](#step-2-dependencies)\n    - [Step 3: Start the server](#step-3-start-the-server)\n      - [a) RESTMockTestRunner](#a-restmocktestrunner)\n      - [b) RESTMockServerStarter](#b-restmockserverstarter)\n    - [Step 4: Specify Mocks](#step-4-specify-mocks)\n      - [a) Files](#a-files)\n      - [b) Strings](#b-strings)\n      - [c) MockResponse](#c-mockresponse)\n      - [c) MockAnswer](#c-mockanswer)\n    - [Step 5: Request Matchers](#step-5-request-matchers)\n    - [Step 6: Specify API Endpoint](#step-6-specify-api-endpoint)\n- [HTTPS](#https)\n- [Response chains](#response-chains)\n- [Response delays](#response-delays)\n    - [Interleaving delays with responses](#interleaving-delays-with-responses)\n- [Request verification](#request-verification)\n- [Logging](#logging)\n- [Android Sample Project](#android-sample-project)\n- [Donation](#donation)\n- [License](#license)\n\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\n\n## Setup\nHere are the basic rules to set up RESTMock for Android\n\n#### Step 1: Repository\nAdd it in your root build.gradle at the end of repositories:\n\n```groovy  \nallprojects {\n\trepositories {\n\t\t...\n\t\tmaven { url \"https://jitpack.io\" }\n\t}\n}\n```\n#### Step 2: Dependencies\nAdd the dependency\n\n```groovy  \ndependencies {\n\tandroidTestImplementation 'com.github.andrzejchm.RESTMock:android:${LATEST_VERSION}' // see \"Releases\" tab for latest version\n}\n```\n\n#### Step 3: Start the server\nIt's good to start server before the tested application starts, there are few methods:\n\n##### a) RESTMockTestRunner\nTo make it simple you can just use the predefined `RESTMockTestRunner` in your UI tests. It extends `AndroidJUnitRunner`:\n\n```groovy\ndefaultConfig {\n\t\t...\n    \ttestInstrumentationRunner 'io.appflate.restmock.android.RESTMockTestRunner'\n    }\n```\n##### b) RESTMockServerStarter\nIf you have your custom test runner and you can't extend `RESTMockTestRunner`, you can always just call the `RESTMockServerStarter`. Actually `RESTMockTestRunner` is doing exactly the same thing:\n\n```java\npublic class MyAppTestRunner extends AndroidJUnitRunner {\n\t...\n\t@Override\n\tpublic void onCreate(Bundle arguments) {\n\t\tsuper.onCreate(arguments);\n\t\tRESTMockServerStarter.startSync(new AndroidAssetsFileParser(getContext()),new AndroidLogger());\n\t\t...\n\t}\n\t...\n}\n\n```\n\n\n#### Step 4: Specify Mocks\n\n##### a) Files\nBy default, the `RESTMockTestRunner` uses `AndroidAssetsFileParser` as a mocks file parser, which reads the files from the assets folder. To make them visible for the RESTMock you have to put them in the correct folder in your project, for example:\n\n\t.../src/androidTest/assets/users/defunkt.json\nThis can be accessed like this:\n\n```java\nRESTMockServer.whenGET(pathContains(\"users/defunkt\"))\n            .thenReturnFile(200, \"users/defunkt.json\");\n```\n\n##### b) Strings\nIf the response You wish to return is simple, you can just specify a string:\n\n```java\nRESTMockServer.whenGET(pathContains(\"users/defunkt\"))\n            .thenReturnString(200, \"{}\");\n```\n##### c) MockResponse\nIf you wish to have a greater control over the response, you can pass the `MockResponse`\n```java\nRESTMockServer.whenGET(pathContains(\"users/defunkt\")).thenReturn(new MockResponse().setBody(\"\").setResponseCode(401).addHeader(\"Header\",\"Value\"));\n```\n##### c) MockAnswer\nYou can always build dynamic `MockResponse`s by using the `RecordedRequest` object\n```java\nRESTMockServer.whenGET(pathContains(\"users/defunkt\")).thenAnswer(new MockAnswer() {\n\n            @Override\n            public MockResponse answer(RecordedRequest request) {\n                    return new MockResponse()\n                            .setBody(request.getHeaders().get(\"header1\"))\n                            .setResponseCode(200);\n            }\n        });\n```\n\n\n#### Step 5: Request Matchers\nYou can either use some of the predefined matchers from `RequestMatchers` util class, or create your own. remember to extend from `RequestMatcher`\n\n#### Step 6: Specify API Endpoint\nThe most important step, in order for your app to communicate with the testServer, you have to specify it as an endpoint for all your API calls. For that, you can use the ` RESTMockServer.getUrl()`. If you use Retrofit, it is as easy as:\n\n```java\nRestAdapter adapter = new RestAdapter.Builder()\n                .baseUrl(RESTMockServer.getUrl())\n                ...\n                .build();\n```\n\ntake a look at [#68](https://github.com/andrzejchm/RESTMock/issues/68) for better reference\n\n## HTTPS\n\nBy default, RESTMockServer will serve responses using Http. In order to use HTTPS, during initialization you have to pass `RESTMockOptions` object with `useHttps` set to true:\n```java\nRESTMockServerStarter.startSync(new AndroidAssetsFileParser(getContext()),new AndroidLogger(), new RESTMockOptions.Builder().useHttps(true).build());\n```\n\nthere is a possibility to set up your own `SSLSocketFactory` and `TrustManager`, if you do not specify those, then default ones will be created for you. You can easly retrieve them with `RESTMockServer.getSSLSocketFactory()` and `RESTMockServer.getTrustManager()` to be able to build your client that will accept the default certificate:\n\n```java\nnew OkHttpClient.Builder().sslSocketFactory(RESTMockServer.getSSLSocketFactory(), RESTMockServer.getTrustManager()).build();\n```\n\nA sample how to use https with RESTMock in android tests can be found in `androidsample` gradle module within this repository.\n\n## Response chains\nYou can chain different responses for a single request matcher, all the `thenReturn*()` methods accept varags parameter with response, or you can call those methods multiple times on a single matcher, examples:\n\n```java\nRESTMockServer.whenGET(pathEndsWith(path))\n                .thenReturnString(\"a single call\")\n                .thenReturnEmpty(200)\n                .thenReturnFile(\"jsonFile.json\");\n```\n\nor \n\n```java\nRESTMockServer.whenGET(pathEndsWith(path))\n                .thenReturnString(\"a single call\", \"answer no 2\", \"answer no 3\");\n```\n\n## Response body delays\nDelaying responses is accomplished with the `delayBody(TimeUnit timeUnit, long delay)` and `delayHeaders(TimeUnit timeUnit, long delay)` method. Delays can be specified in chain, just like chaining responses:\n \n```java\nRESTMockServer.whenGET(pathEndsWith(path))\n                .thenReturnString(\"a single call\")\n                .delayBody(TimeUnit.SECONDS, 5)\n                .delayBody(TimeUnit.SECONDS, 10)\n                .delayBody(TimeUnit.SECONDS, 15);\n```\n\nor\n\n```java\nRESTMockServer.whenGET(pathEndsWith(path))\n                .thenReturnString(\"a single call\")\n                .delayBody(TimeUnit.SECONDS, 5, 10, 15);\n```\n\nWhich will result in 1st response body being delayed by 5 seconds, 2nd response by 10 seconds and 3rd, 4th, 5th... by 15 seconds.\n\n## Response header delays\n\nMechanics of the `responseHeader(...)` method are the same as those in `responseBody(...)`. The only difference is that response headers are being delivered with a delay. This comes handy if your app is acting on response headers, which would've been delivered immediately if you used the `delayBody(...)` method.\n\n\n#### Interleaving delays with responses\nCheck out this example:\n\n```java\nRESTMockServer.whenGET(pathEndsWith(path))\n                .thenReturnString(\"1st call\")\n                .delay(TimeUnit.SECONDS, 5)\n                .thenReturnString(\"2nd call\")\n                .delay(TimeUnit.SECONDS, 10)\n                .delay(TimeUnit.SECONDS, 15)\n                .thenReturnString(\"3rd call\")\n                .delay(TimeUnit.SECONDS, 20, 30, 40)\n```\n\nthis will result in `1st call` being delayed by 5 seconds, `2nd call` delayed by 10 seconds, `3rd call` delayed by 15 seconds, another one by 20 seconds, and another by 30 seconds, and then every consecutive response with 40 seconds delay\n\n## Request verification\nIt is possible to verify which requests were called and how many times thanks to `RequestsVerifier`. All you have to do is call one of these:\n\n```java\n//cheks if the GET request was invoked exactly 2 times\nRequestsVerifier.verifyGET(pathEndsWith(\"users\")).exactly(2);\n\n//cheks if the GET request was invoked at least 3 times\nRequestsVerifier.verifyGET(pathEndsWith(\"users\")).atLeast(3);\n\n//cheks if the GET request was invoked exactly 1 time\nRequestsVerifier.verifyGET(pathEndsWith(\"users\")).invoked();\n\n//cheks if the GET request was never invoked\nRequestsVerifier.verifyGET(pathEndsWith(\"users\")).never();\n```\n\nAdditionaly, you can manualy inspect requests received by RESTMockServer. All you have to do is to obtain them trough:\n\n```java\n//gets 5 most recent requests received. (ordered from oldest to newest)\nRequestsVerifier.takeLast(5);\n\n//gets 5 oldest requests received. (ordered from oldest to newest)\nRequestsVerifier.takeFirst(5);\n\n//gets all GET requests.  (ordered from oldest to newest)\nRequestsVerifier.takeAllMatching(isGET());\n```\n\n## Logging\nRESTMock supports logging events. You just have to provide the RESTMock with the implementation of `RESTMockLogger`. For Android there is an `AndroidLogger` implemented already. All you have to do is use the `RESTMockTestRunner` or call\n\n```java\nRESTMockServerStarter.startSync(new AndroidAssetsFileParser(getContext()),new AndroidLogger(), new RESTMockOptions());\n```\n\nor\n\n```java\nRESTMockServer.enableLogging(RESTMockLogger)\nRESTMockServer.disableLogging()\n```\n\n## Android Sample Project\nYou can check out the sample Android app with tests [here](androidsample/)\n\n## Donation\nIf you think the library is awesome and want to buy me a beer, you can do so by sending some...\n* ![Ethereum](https://s2.coinmarketcap.com/static/img/coins/16x16/1027.png) **ETH** here: `0xf7354a0F7B34A380f6d68a2661bE465C10D6AEd7`\n* ![Bitcoin](https://s2.coinmarketcap.com/static/img/coins/16x16/1.png) **BTC** here: `12bU3BMibFqbBBymaftXTDnoHojFymD7a6`\n* ![NEO](https://s2.coinmarketcap.com/static/img/coins/16x16/1376.png) **NEO** or **GAS** here: `AX1ovzRN2N28WJrtehjYXjwtHSvcqva6Ri`\n\n## License\n\n\tCopyright (C) 2016 Appflate.io\n\n \tLicensed under the Apache License, Version 2.0 (the \"License\");\n \tyou may not use this file except in compliance with the License.\n \tYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\n\tUnless required by applicable law or agreed to in writing, software\n\tdistributed under the License is distributed on an \"AS IS\" BASIS,\n\tWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\tSee the License for the specific language governing permissions and\n\tlimitations under the License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrzejchm%2FRESTMock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandrzejchm%2FRESTMock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandrzejchm%2FRESTMock/lists"}