├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── art └── how_it_works.png ├── build.gradle ├── checkstyle.xml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── mockwebserverplus ├── build.gradle ├── gradle.properties └── src │ ├── main │ └── java │ │ └── com │ │ └── orhanobut │ │ └── mockwebserverplus │ │ ├── Fixture.java │ │ ├── MockWebServerPlus.java │ │ ├── Parser.java │ │ └── YamlParser.java │ └── test │ ├── java │ ├── com │ │ └── orhanobut │ │ │ └── mockwebserverplus │ │ │ ├── FixtureTest.java │ │ │ └── MockWebServerPlusTest.java │ └── fixtures │ │ └── Fixtures.java │ └── resources │ └── fixtures │ ├── body │ └── simple_body.json │ ├── delayed_1000_ms.yaml │ ├── simple.yaml │ ├── simple_body_file.yaml │ ├── simple_no_body.yaml │ ├── simple_no_headers.yaml │ ├── simple_no_status_code.yaml │ └── simple_with_delay.yaml ├── sample ├── build.gradle └── src │ ├── main │ └── AndroidManifest.xml │ └── test │ ├── java │ ├── com │ │ └── orhanobut │ │ │ └── sample │ │ │ └── FooTest.java │ └── fixtures │ │ └── Fixtures.java │ └── resources │ └── fixtures │ └── simple.yaml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | # Files for the Dalvik VM 5 | *.dex 6 | # Java class files 7 | *.class 8 | # Generated files 9 | bin/ 10 | gen/ 11 | # Gradle files 12 | .gradle/ 13 | build/ 14 | # Local configuration file (sdk path, etc) 15 | local.properties 16 | # Proguard folder generated by Eclipse 17 | proguard/ 18 | # Log Files 19 | *.log 20 | .gradle 21 | /local.properties 22 | /.idea/workspace.xml 23 | /.idea/libraries 24 | .DS_Store 25 | /build 26 | .idea/ 27 | *.iml -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: oraclejdk8 3 | 4 | android: 5 | components: 6 | - tools 7 | - platform-tools 8 | - build-tools-25.0.2 9 | - android-23 10 | - android-24 11 | 12 | script: 13 | - ./gradlew check -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### mockwebserver + 2 | 3 | #### Issue 4 | MockWebServer is a great tool for mocking network requests/responses. 5 | In order to add response, you need to set MockResponse body along with all 6 | properties you need 7 | 8 | ```java 9 | @Rule public MockWebServer server = new MockWebServer(); 10 | 11 | @Test public void uglyTest() { 12 | server.enqueue(new MockResponse() 13 | .setStatusCode(200) 14 | .setBody({ 15 | "array": [ 16 | 1, 17 | 2, 18 | 3 19 | ], 20 | "boolean": true, 21 | "null": null, 22 | "number": 123, 23 | "object": { 24 | "a": "b", 25 | "c": "d", 26 | "e": "f" 27 | }, 28 | "string": "Hello World" 29 | }) 30 | .addHeader("HeaderKey:HeaderValue") 31 | .responseDelay(3, SECONDS) 32 | ); 33 | 34 | // execute request 35 | // assert 36 | // verify 37 | } 38 | ``` 39 | 40 | Imagine it with huge json responses. It will obscure the method content and will be barely readable. 41 | 42 | 43 | #### Solution 44 | In order to make it more readable, you can use fixtures. Move away your response to the fixtures and just reference them. 45 | MockWebServerPlus is a wrapper which contains MockWebServer with fixtures feature. 46 | 47 | ##### Create a fixture yaml file under resources/fixtures 48 | 49 | ``` 50 | src 51 | ├── test 52 | │ ├── java 53 | │ ├── resources 54 | │ │ ├── fixtures 55 | │ │ │ ├── foo_success.yaml 56 | │ │ │ ├── foo_failure.yaml 57 | ``` 58 | 59 | ```yaml 60 | statusCode : 200 // as the name says 61 | delay: 0 // delays the response 62 | headers: // adds to the response 63 | - 'Auth:auth' 64 | - 'key:value' 65 | body: 'common/body_file.json' // can be any path under /fixtures folder 66 | // or inline 67 | body: > // can be any text, json, plain etc. Use > letter for scalar text 68 | { 69 | "array": [ 70 | 1, 71 | 2, 72 | 3 73 | ], 74 | "boolean": true, 75 | "null": null, 76 | "number": 123, 77 | "object": { 78 | "a": "b", 79 | "c": "d", 80 | "e": "f" 81 | }, 82 | "string": "Hello World" 83 | } 84 | ``` 85 | 86 | ### Use the file name to reference it. That's it! 87 | 88 | ```java 89 | @Rule public MockWebServerPlus server = new MockWebServerPlus(); 90 | 91 | @Test public void readableTest() { 92 | server.enqueue("foo_success"); 93 | 94 | // execute request 95 | // assert 96 | // verify 97 | } 98 | ``` 99 | 100 | #### Use the generated Fixtures.java to reference your fixtures. Read the Generate Fixtures.java part 101 | ```java 102 | server.enqueue(Fixtures.FOO_SUCCESS); 103 | ``` 104 | 105 | ### Enqueue multiple response 106 | ```java 107 | server.enqueue(Fixtures.FOO_SUCCESS, Fixtures.USER_REGISTER_SUCCESS); 108 | ``` 109 | 110 | ### Custom Dispatcher 111 | You may wish to use a custom dispatcher with the mock web server. 112 | 113 | Fixtures can be used directly inside a Dispatcher: 114 | 115 | ``` 116 | new Dispatcher() { 117 | @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { 118 | return Fixture.parseFrom("simple).toMockResponse(); 119 | } 120 | } 121 | ``` 122 | 123 | ### Generate Fixtures.java 124 | You can always use plain text to reference your fixtures. 125 | 126 | ```java 127 | server.enqueue("foo_success"); 128 | ``` 129 | 130 | but you can also generate Fixtures.java file to have all of them with a task. This will make your code more type-safe. 131 | Put the following task into your build.gradle file and execute it when you add/modify your fixture resources. 132 | 133 | ```groovy 134 | task generateFixtures(dependsOn: copyTestResources) << { 135 | def directory = projectDir.path + '/src/test/java' 136 | new File(directory + '/fixtures').mkdir() 137 | def path = directory + "/fixtures/Fixtures.java" 138 | 139 | def builder = '' << '' 140 | builder.append("package fixtures;\n\n") 141 | builder.append("public class Fixtures {\n\n") 142 | builder.append(" private Fixtures() {\n") 143 | builder.append(" //no instance\n") 144 | builder.append(" }\n\n") 145 | 146 | def resources = android.sourceSets.test.resources.srcDirs.getAt(0) 147 | if (resources.size() > 0) { 148 | resources.eachDirMatch("fixtures") { dir -> 149 | def fixturesFile = dir 150 | fixturesFile.eachFile(FileType.FILES) { file -> 151 | if (file.name.endsWith(".yaml")) { 152 | String fileName = file.name.split('\\.')[0] 153 | builder.append(" public static final String ") 154 | .append(fileName.toUpperCase()) 155 | .append(" = ") 156 | .append('\"') 157 | .append(fileName) 158 | .append('\";\n') 159 | } 160 | } 161 | } 162 | } 163 | builder.append("}\n") 164 | 165 | new File(path).write(builder.toString()) 166 | } 167 | 168 | ``` 169 | 170 | Above solution will generate Fixtures.java when you execute it manually. But you might forget to execute it, you can 171 | make it dependent for any task to make it automated. Whenever preBuild is executed, it will also execute this task 172 | 173 | ```groovy 174 | preBuild.dependsOn generateFixtures 175 | ``` 176 | 177 | ### Install 178 | ```groovy 179 | testCompile 'com.orhanobut:mockwebserverplus:2.0.0' 180 | 181 | // This is optional, but in order to be up-to-date with OkHttp changes, you can use the latest version 182 | testCompile 'com.squareup.okhttp3:mockwebserver:3.7.0' 183 | ``` 184 | 185 | #### Other proxy methods 186 | ```java 187 | MockWebServerPlus.server() // returns MockWebServer instance 188 | MockWebServerPlus.takeRequest() // returns RecordedRequest 189 | MockWebServerPlus.url(String path) // returns url to execute 190 | MockWebServerPlus.setDispatcher(Dispatcher dispatcher) // any custom dispatcher 191 | MockWebServerPlus.enqueue(SocketPolicy socketPolicy) // Useful for network errors, such as DISCONNECT etc 192 | ``` 193 | 194 | ### Get the fixture object 195 | ```java 196 | Fixture fixture = Fixture.parseFrom(Fixtures.SIMPLE); 197 | ``` 198 | 199 | ### For non-android modules 200 | For non-android modules, you may need to add the following tasks to copy your resources into classes dir 201 | ```groovy 202 | task copyTestResources(type: Copy) { 203 | from sourceSets.test.resources 204 | into sourceSets.test.output.classesDir 205 | } 206 | ``` 207 | 208 | ### How it works 209 | 210 | 211 | Also notice that accessing sourceSets should be without android. 212 | 213 | #### Credits 214 | [MockWebServer](https://github.com/square/okhttp/tree/master/mockwebserver) from Square 215 | 216 | ### License 217 |
218 | Copyright 2017 Orhan Obut
219 | 
220 | Licensed under the Apache License, Version 2.0 (the "License");
221 | you may not use this file except in compliance with the License.
222 | You may obtain a copy of the License at
223 | 
224 |    http://www.apache.org/licenses/LICENSE-2.0
225 | 
226 | Unless required by applicable law or agreed to in writing, software
227 | distributed under the License is distributed on an "AS IS" BASIS,
228 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
229 | See the License for the specific language governing permissions and
230 | limitations under the License.
231 | 
232 | -------------------------------------------------------------------------------- /art/how_it_works.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/mockwebserverplus/bb2c5cb4eece98745688ec562486b6bfc5d1b6c7/art/how_it_works.png -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.3.2' 9 | classpath 'org.gradle.api.plugins:gradle-nexus-plugin:0.7' 10 | 11 | // NOTE: Do not place your application dependencies here; they belong 12 | // in the individual module build.gradle files 13 | } 14 | } 15 | 16 | allprojects { 17 | version = VERSION_NAME 18 | group = GROUP 19 | 20 | repositories { 21 | jcenter() 22 | } 23 | } 24 | 25 | task clean(type: Delete) { 26 | delete rootProject.buildDir 27 | } 28 | -------------------------------------------------------------------------------- /checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=1.0.0 2 | GROUP=com.orhanobut 3 | 4 | POM_DESCRIPTION=MockWebServerPlus 5 | POM_URL=https://github.com/orhanobut/mockwebserverplus 6 | POM_SCM_URL=https://github.com/orhanobut/mockwebserverplus 7 | POM_SCM_CONNECTION=scm:git@https://github.com/orhanobut/mockwebserverplus.git 8 | POM_SCM_DEV_CONNECTION=scm:git@https://github.com/orhanobut/mockwebserverplus.git 9 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 10 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 11 | POM_LICENCE_DIST=repo 12 | POM_DEVELOPER_ID=nr4bt 13 | POM_DEVELOPER_NAME=Orhan Obut -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/mockwebserverplus/bb2c5cb4eece98745688ec562486b6bfc5d1b6c7/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Jan 10 17:25:12 CET 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /mockwebserverplus/build.gradle: -------------------------------------------------------------------------------- 1 | import groovy.io.FileType 2 | 3 | apply plugin: 'java' 4 | apply plugin: 'nexus' 5 | apply plugin: 'checkstyle' 6 | 7 | task checkstyle(type: Checkstyle) { 8 | configFile = rootProject.file('checkstyle.xml') 9 | source 'src' 10 | include '**/*.java' 11 | exclude '**/gen/**' 12 | 13 | classpath = files() 14 | } 15 | checkstyle { 16 | toolVersion = '7.2' 17 | } 18 | 19 | compileJava { 20 | sourceCompatibility = JavaVersion.VERSION_1_7 21 | targetCompatibility = JavaVersion.VERSION_1_7 22 | } 23 | 24 | task copyTestResources(type: Copy, group: 'fixtures') { 25 | from sourceSets.test.resources 26 | into sourceSets.test.output.classesDir 27 | } 28 | 29 | task generateFixtures(dependsOn: copyTestResources, group: 'fixtures') << { 30 | def directory = projectDir.path + '/src/test/java' 31 | new File(directory + '/fixtures').mkdir() 32 | def path = directory + "/fixtures/Fixtures.java" 33 | 34 | def builder = '' << '' 35 | builder.append("package fixtures;\n\n") 36 | builder.append("public class Fixtures {\n\n") 37 | builder.append(" private Fixtures() {\n") 38 | builder.append(" //no instance\n") 39 | builder.append(" }\n\n") 40 | 41 | def resources = sourceSets.test.resources.srcDirs.getAt(0) 42 | if (resources.size() > 0) { 43 | resources.eachDirMatch("fixtures") { dir -> 44 | def fixturesFile = dir 45 | fixturesFile.eachFile(FileType.FILES) { file -> 46 | if (file.name.endsWith(".yaml")) { 47 | String fileName = file.name.split('\\.')[0] 48 | builder.append(" public static final String ") 49 | .append(fileName.toUpperCase()) 50 | .append(" = ") 51 | .append('\"') 52 | .append(fileName) 53 | .append('\";\n') 54 | } 55 | } 56 | } 57 | } 58 | builder.append("}\n") 59 | 60 | new File(path).write(builder.toString()) 61 | } 62 | 63 | compileTestJava.dependsOn generateFixtures 64 | 65 | dependencies { 66 | compile 'junit:junit:4.12' 67 | compile('com.squareup.okhttp3:mockwebserver:3.7.0') { 68 | exclude group: "junit" 69 | } 70 | compile('org.yaml:snakeyaml:1.14') { 71 | transitive false 72 | } 73 | 74 | testCompile 'org.assertj:assertj-core:2.4.0' 75 | testCompile "org.mockito:mockito-core:1.9.5" 76 | testCompile 'com.squareup.okhttp3:okhttp:3.7.0' 77 | } 78 | 79 | modifyPom { 80 | project { 81 | name POM_NAME 82 | description POM_DESCRIPTION 83 | url POM_URL 84 | 85 | scm { 86 | url POM_SCM_URL 87 | connection POM_SCM_CONNECTION 88 | developerConnection POM_SCM_DEV_CONNECTION 89 | } 90 | 91 | licenses { 92 | license { 93 | name POM_LICENCE_NAME 94 | url POM_LICENCE_URL 95 | Distribution POM_LICENCE_DIST 96 | } 97 | } 98 | 99 | developers { 100 | developer { 101 | id POM_DEVELOPER_ID 102 | name POM_DEVELOPER_NAME 103 | } 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /mockwebserverplus/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=MockWebServerPlus 2 | POM_ARTIFACT_ID=mockwebserverplus 3 | POM_PACKAGING=jar -------------------------------------------------------------------------------- /mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/Fixture.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.mockwebserverplus; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.util.List; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | import okhttp3.mockwebserver.MockResponse; 11 | 12 | /** 13 | * A value container that holds all information about the fixture file. 14 | */ 15 | public class Fixture { 16 | 17 | public int statusCode; 18 | public String body; 19 | public List headers; 20 | public int delay; 21 | 22 | /** 23 | * Parse the given filename and returns the Fixture object. 24 | * 25 | * @param fileName filename should not contain extension or relative path. ie: login 26 | */ 27 | public static Fixture parseFrom(String fileName) { 28 | return parseFrom(fileName, new YamlParser()); 29 | } 30 | 31 | 32 | /** 33 | * Parse the given filename and returns the Fixture object. 34 | * 35 | * @param fileName filename should not contain extension or relative path. ie: login 36 | * @param parser parser is required for parsing operation, it should not be null 37 | */ 38 | public static Fixture parseFrom(String fileName, Parser parser) { 39 | if (fileName == null) { 40 | throw new NullPointerException("File name should not be null"); 41 | } 42 | String path = "fixtures/" + fileName + ".yaml"; 43 | InputStream inputStream = openPathAsStream(path); 44 | Fixture result = parser.parse(inputStream); 45 | 46 | if (result.body != null && !result.body.startsWith("{")) { 47 | String bodyPath = "fixtures/" + result.body; 48 | try { 49 | result.body = readPathIntoString(bodyPath); 50 | } catch (IOException e) { 51 | throw new IllegalStateException("Error reading body: " + bodyPath, e); 52 | } 53 | } 54 | return result; 55 | } 56 | 57 | private static InputStream openPathAsStream(String path) { 58 | ClassLoader loader = Thread.currentThread().getContextClassLoader(); 59 | InputStream inputStream = loader.getResourceAsStream(path); 60 | 61 | if (inputStream == null) { 62 | throw new IllegalStateException("Invalid path: " + path); 63 | } 64 | 65 | return inputStream; 66 | } 67 | 68 | private static String readPathIntoString(String path) throws IOException { 69 | InputStream inputStream = openPathAsStream(path); 70 | BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 71 | StringBuilder out = new StringBuilder(); 72 | int read; 73 | while ((read = reader.read()) != -1) { 74 | out.append((char) read); 75 | } 76 | reader.close(); 77 | 78 | return out.toString(); 79 | } 80 | 81 | public MockResponse toMockResponse() { 82 | MockResponse mockResponse = new MockResponse(); 83 | if (this.statusCode != 0) { 84 | mockResponse.setResponseCode(this.statusCode); 85 | } 86 | if (this.body != null) { 87 | mockResponse.setBody(this.body); 88 | } 89 | if (this.delay != 0) { 90 | mockResponse.setBodyDelay(this.delay, TimeUnit.MILLISECONDS); 91 | } 92 | if (this.headers != null) { 93 | for (String header : this.headers) { 94 | mockResponse.addHeader(header); 95 | } 96 | } 97 | return mockResponse; 98 | } 99 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/MockWebServerPlus.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.mockwebserverplus; 2 | 3 | import org.junit.rules.TestRule; 4 | import org.junit.runner.Description; 5 | import org.junit.runners.model.Statement; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import okhttp3.mockwebserver.Dispatcher; 11 | import okhttp3.mockwebserver.MockResponse; 12 | import okhttp3.mockwebserver.MockWebServer; 13 | import okhttp3.mockwebserver.RecordedRequest; 14 | import okhttp3.mockwebserver.SocketPolicy; 15 | 16 | /** 17 | * A wrapper for {@link MockWebServer} with more features 18 | */ 19 | public class MockWebServerPlus implements TestRule { 20 | 21 | private final MockWebServer mockWebServer; 22 | private final Parser parser = new YamlParser(); 23 | 24 | public MockWebServerPlus() { 25 | this.mockWebServer = new MockWebServer(); 26 | } 27 | 28 | public MockWebServerPlus(MockWebServer mockWebServer) { 29 | this.mockWebServer = mockWebServer; 30 | } 31 | 32 | @Override public Statement apply(final Statement base, final Description description) { 33 | return mockWebServer.apply(base, description); 34 | } 35 | 36 | /** 37 | * Given paths will be parsed to fixtures and added to the queue. Can be multiple 38 | */ 39 | public List enqueue(String... paths) { 40 | if (paths == null) { 41 | return null; 42 | } 43 | List mockResponseList = new ArrayList<>(); 44 | for (String path : paths) { 45 | Fixture fixture = Fixture.parseFrom(path, parser); 46 | MockResponse mockResponse = fixture.toMockResponse(); 47 | mockWebServer.enqueue(mockResponse); 48 | mockResponseList.add(mockResponse); 49 | } 50 | return mockResponseList; 51 | } 52 | 53 | /** 54 | * Given policy will be enqueued as MockResponse 55 | */ 56 | public MockResponse enqueue(SocketPolicy socketPolicy) { 57 | MockResponse mockResponse = new MockResponse().setSocketPolicy(socketPolicy); 58 | mockWebServer.enqueue(mockResponse); 59 | return mockResponse; 60 | } 61 | 62 | /** 63 | * Given response will be enqueued 64 | */ 65 | public void enqueue(MockResponse response) { 66 | mockWebServer.enqueue(response); 67 | } 68 | 69 | /** 70 | * Returns the url as endpoint 71 | * 72 | * @param path url path 73 | */ 74 | public String url(String path) { 75 | return mockWebServer.url(path).toString(); 76 | } 77 | 78 | /** 79 | * Returns the recorded request after execution 80 | */ 81 | public RecordedRequest takeRequest() throws InterruptedException { 82 | return mockWebServer.takeRequest(); 83 | } 84 | 85 | /** 86 | * A proxy method for MockWebServer dispatcher 87 | */ 88 | public void setDispatcher(Dispatcher dispatcher) { 89 | mockWebServer.setDispatcher(dispatcher); 90 | } 91 | 92 | /** 93 | * Returns the wrapped MockWebServer instance. 94 | */ 95 | public MockWebServer server() { 96 | return mockWebServer; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/Parser.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.mockwebserverplus; 2 | 3 | import java.io.InputStream; 4 | 5 | /** 6 | * Used to parse InputStream to {@link Fixture} object 7 | * Any implementation should meet the rule above 8 | */ 9 | interface Parser { 10 | 11 | Fixture parse(InputStream inputStream); 12 | } 13 | -------------------------------------------------------------------------------- /mockwebserverplus/src/main/java/com/orhanobut/mockwebserverplus/YamlParser.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.mockwebserverplus; 2 | 3 | import org.yaml.snakeyaml.Yaml; 4 | 5 | import java.io.InputStream; 6 | 7 | class YamlParser implements Parser { 8 | 9 | @Override public Fixture parse(InputStream inputStream) { 10 | return new Yaml().loadAs(inputStream, Fixture.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /mockwebserverplus/src/test/java/com/orhanobut/mockwebserverplus/FixtureTest.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.mockwebserverplus; 2 | 3 | import org.junit.Test; 4 | 5 | import fixtures.Fixtures; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | import static org.assertj.core.api.Assertions.fail; 9 | 10 | public class FixtureTest { 11 | 12 | final Parser parser = new YamlParser(); 13 | 14 | @Test public void parseWithoutParser() { 15 | Fixture fixture = Fixture.parseFrom(Fixtures.SIMPLE_WITH_DELAY); 16 | 17 | assertThat(fixture.statusCode).isEqualTo(200); 18 | assertThat(fixture.delay).isEqualTo(300); 19 | assertThat(fixture.body).isEqualTo("{result:{}}"); 20 | assertThat(fixture.headers).containsExactly("Auth:auth", "key:value"); 21 | } 22 | 23 | @Test public void parseFixtureFromYaml() { 24 | Fixture fixture = Fixture.parseFrom(Fixtures.SIMPLE_WITH_DELAY, parser); 25 | 26 | assertThat(fixture.statusCode).isEqualTo(200); 27 | assertThat(fixture.delay).isEqualTo(300); 28 | assertThat(fixture.body).isEqualTo("{result:{}}"); 29 | assertThat(fixture.headers).containsExactly("Auth:auth", "key:value"); 30 | } 31 | 32 | @Test public void invalidPathThrowsExceptionOnParse() { 33 | try { 34 | Fixture.parseFrom("invalid_path", parser); 35 | fail("should fail"); 36 | } catch (Exception e) { 37 | assertThat(e).hasMessage("Invalid path: fixtures/invalid_path.yaml"); 38 | } 39 | 40 | try { 41 | Fixture.parseFrom(null, parser); 42 | fail("should fail"); 43 | } catch (Exception e) { 44 | assertThat(e).hasMessage("File name should not be null"); 45 | } 46 | } 47 | 48 | @Test public void parseFixtureWithBodyReference() { 49 | Fixture fixture = Fixture.parseFrom(Fixtures.SIMPLE_BODY_FILE, parser); 50 | 51 | assertThat(fixture.statusCode).isEqualTo(200); 52 | assertThat(fixture.delay).isEqualTo(0); 53 | assertThat(fixture.body).isEqualTo("{\n" + 54 | " \"array\": [\n" + 55 | " 1,\n" + 56 | " 2,\n" + 57 | " 3\n" + 58 | " ],\n" + 59 | " \"boolean\": true,\n" + 60 | " \"null\": null,\n" + 61 | " \"number\": 123,\n" + 62 | " \"object\": {\n" + 63 | " \"a\": \"b\",\n" + 64 | " \"c\": \"d\",\n" + 65 | " \"e\": \"f\"\n" + 66 | " },\n" + 67 | " \"string\": \"Hello World\"\n" + 68 | "}"); 69 | assertThat(fixture.headers).containsExactly("Auth:auth", "key:value"); 70 | } 71 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/test/java/com/orhanobut/mockwebserverplus/MockWebServerPlusTest.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.mockwebserverplus; 2 | 3 | import org.junit.Rule; 4 | import org.junit.Test; 5 | 6 | import java.io.IOException; 7 | 8 | import fixtures.Fixtures; 9 | import okhttp3.OkHttpClient; 10 | import okhttp3.Request; 11 | import okhttp3.Response; 12 | import okhttp3.mockwebserver.Dispatcher; 13 | import okhttp3.mockwebserver.MockResponse; 14 | import okhttp3.mockwebserver.MockWebServer; 15 | import okhttp3.mockwebserver.QueueDispatcher; 16 | import okhttp3.mockwebserver.RecordedRequest; 17 | import okhttp3.mockwebserver.SocketPolicy; 18 | 19 | import static com.orhanobut.mockwebserverplus.MockWebServerPlusTest.AssertFixture.assertFixture; 20 | import static org.assertj.core.api.Assertions.assertThat; 21 | import static org.mockito.Matchers.any; 22 | import static org.mockito.Mockito.spy; 23 | import static org.mockito.Mockito.verify; 24 | 25 | public class MockWebServerPlusTest { 26 | 27 | private static final String JSON_RESPONSE = "{\n" + 28 | " \"array\": [\n" + 29 | " 1,\n" + 30 | " 2,\n" + 31 | " 3\n" + 32 | " ],\n" + 33 | " \"boolean\": true,\n" + 34 | " \"null\": null,\n" + 35 | " \"number\": 123,\n" + 36 | " \"object\": {\n" + 37 | " \"a\": \"b\",\n" + 38 | " \"c\": \"d\",\n" + 39 | " \"e\": \"f\"\n" + 40 | " },\n" + 41 | " \"string\": \"Hello World\"\n" + 42 | "}"; 43 | 44 | @Rule public MockWebServer mockWebServer = new MockWebServer(); 45 | 46 | final MockWebServerPlus server = new MockWebServerPlus(mockWebServer); 47 | final OkHttpClient httpClient = new OkHttpClient(); 48 | 49 | @Test public void useDefaultMockWebServer() { 50 | assertThat(new MockWebServerPlus().server()).isNotNull(); 51 | } 52 | 53 | @Test public void generateValidUrl() { 54 | assertThat(server.url("")).isNotNull(); 55 | } 56 | 57 | @Test public void enqueueSingleResponse() throws Exception { 58 | server.enqueue(Fixtures.SIMPLE); 59 | 60 | Response response = execute(); 61 | 62 | assertFixture(response) 63 | .body(JSON_RESPONSE) 64 | .statusCode(200) 65 | .header("Auth", "auth") 66 | .header("key", "value"); 67 | } 68 | 69 | @Test public void enqueueMultipleResponse() throws Exception { 70 | server.enqueue(Fixtures.SIMPLE, Fixtures.SIMPLE); 71 | 72 | Response response = execute(); 73 | 74 | assertFixture(response) 75 | .body(JSON_RESPONSE) 76 | .statusCode(200) 77 | .header("Auth", "auth") 78 | .header("key", "value"); 79 | 80 | Response response2 = execute(); 81 | 82 | assertFixture(response2) 83 | .body(JSON_RESPONSE) 84 | .statusCode(200) 85 | .header("Auth", "auth") 86 | .header("key", "value"); 87 | } 88 | 89 | @Test public void enqueueWithoutHeaders() throws Exception { 90 | server.enqueue(Fixtures.SIMPLE_NO_HEADERS); 91 | 92 | Response response = execute(); 93 | 94 | assertFixture(response) 95 | .body(JSON_RESPONSE) 96 | .statusCode(200); 97 | } 98 | 99 | @Test public void enqueueWithoutBody() throws Exception { 100 | server.enqueue(Fixtures.SIMPLE_NO_BODY); 101 | 102 | Response response = execute(); 103 | 104 | assertFixture(response).statusCode(200); 105 | } 106 | 107 | @Test public void enqueueWithoutStatusCode() throws Exception { 108 | server.enqueue(Fixtures.SIMPLE_NO_STATUS_CODE); 109 | 110 | Response response = execute(); 111 | 112 | assertFixture(response) 113 | .body(JSON_RESPONSE) 114 | .statusCode(200); 115 | } 116 | 117 | @Test public void enqueueSocketPolicy() throws IOException { 118 | server.enqueue(SocketPolicy.KEEP_OPEN); 119 | QueueDispatcher dispatcher = new QueueDispatcher(); 120 | server.setDispatcher(dispatcher); 121 | 122 | MockResponse mockResponse = dispatcher.peek(); 123 | 124 | assertThat(mockResponse.getSocketPolicy()).isEqualTo(SocketPolicy.KEEP_OPEN); 125 | } 126 | 127 | @Test public void interceptDispatch() throws InterruptedException, IOException { 128 | Dispatcher dispatcher = spy(new QueueDispatcher()); 129 | server.setDispatcher(dispatcher); 130 | server.enqueue(new MockResponse()); 131 | 132 | execute(); 133 | 134 | verify(dispatcher).dispatch(any(RecordedRequest.class)); 135 | } 136 | 137 | @Test public void getRecordedRequest() throws IOException, InterruptedException { 138 | server.enqueue(new MockResponse()); 139 | 140 | execute(); 141 | 142 | RecordedRequest recordedRequest = server.takeRequest(); 143 | 144 | assertThat(recordedRequest).isNotNull(); 145 | } 146 | 147 | @Test public void getMockServerInstance() { 148 | assertThat(server.server()).isEqualTo(mockWebServer); 149 | } 150 | 151 | private Response execute() throws IOException { 152 | return execute(server.url("/")); 153 | } 154 | 155 | private Response execute(String url) throws IOException { 156 | Request request = new Request.Builder() 157 | .url(server.url(url)) 158 | .get() 159 | .build(); 160 | 161 | return httpClient.newCall(request).execute(); 162 | } 163 | 164 | static class AssertFixture { 165 | private final Response response; 166 | 167 | private AssertFixture(Response response) { 168 | this.response = response; 169 | } 170 | 171 | static AssertFixture assertFixture(Response response) { 172 | return new AssertFixture(response); 173 | } 174 | 175 | AssertFixture body(String body) throws IOException { 176 | assertThat(response.body().string()).isEqualTo(body); 177 | return this; 178 | } 179 | 180 | AssertFixture statusCode(int statusCode) { 181 | assertThat(response.code()).isEqualTo(statusCode); 182 | return this; 183 | } 184 | 185 | AssertFixture header(String key, String value) { 186 | assertThat(response.header(key)).isEqualTo(value); 187 | return this; 188 | } 189 | } 190 | 191 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/test/java/fixtures/Fixtures.java: -------------------------------------------------------------------------------- 1 | package fixtures; 2 | 3 | public class Fixtures { 4 | 5 | private Fixtures() { 6 | //no instance 7 | } 8 | 9 | public static final String DELAYED_1000_MS = "delayed_1000_ms"; 10 | public static final String SIMPLE = "simple"; 11 | public static final String SIMPLE_BODY_FILE = "simple_body_file"; 12 | public static final String SIMPLE_NO_BODY = "simple_no_body"; 13 | public static final String SIMPLE_NO_HEADERS = "simple_no_headers"; 14 | public static final String SIMPLE_NO_STATUS_CODE = "simple_no_status_code"; 15 | public static final String SIMPLE_WITH_DELAY = "simple_with_delay"; 16 | } 17 | -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/body/simple_body.json: -------------------------------------------------------------------------------- 1 | { 2 | "array": [ 3 | 1, 4 | 2, 5 | 3 6 | ], 7 | "boolean": true, 8 | "null": null, 9 | "number": 123, 10 | "object": { 11 | "a": "b", 12 | "c": "d", 13 | "e": "f" 14 | }, 15 | "string": "Hello World" 16 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/delayed_1000_ms.yaml: -------------------------------------------------------------------------------- 1 | delay: 1000 -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/simple.yaml: -------------------------------------------------------------------------------- 1 | statusCode : 200 2 | delay: 0 3 | headers: 4 | - 'Auth:auth' 5 | - 'key:value' 6 | body: > 7 | { 8 | "array": [ 9 | 1, 10 | 2, 11 | 3 12 | ], 13 | "boolean": true, 14 | "null": null, 15 | "number": 123, 16 | "object": { 17 | "a": "b", 18 | "c": "d", 19 | "e": "f" 20 | }, 21 | "string": "Hello World" 22 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/simple_body_file.yaml: -------------------------------------------------------------------------------- 1 | statusCode : 200 2 | delay: 0 3 | headers: 4 | - 'Auth:auth' 5 | - 'key:value' 6 | body: 'body/simple_body.json' -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/simple_no_body.yaml: -------------------------------------------------------------------------------- 1 | statusCode : 200 -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/simple_no_headers.yaml: -------------------------------------------------------------------------------- 1 | statusCode : 200 2 | delay: 0 3 | body: > 4 | { 5 | "array": [ 6 | 1, 7 | 2, 8 | 3 9 | ], 10 | "boolean": true, 11 | "null": null, 12 | "number": 123, 13 | "object": { 14 | "a": "b", 15 | "c": "d", 16 | "e": "f" 17 | }, 18 | "string": "Hello World" 19 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/simple_no_status_code.yaml: -------------------------------------------------------------------------------- 1 | delay: 0 2 | headers: 3 | - 'Auth:auth' 4 | - 'key:value' 5 | body: > 6 | { 7 | "array": [ 8 | 1, 9 | 2, 10 | 3 11 | ], 12 | "boolean": true, 13 | "null": null, 14 | "number": 123, 15 | "object": { 16 | "a": "b", 17 | "c": "d", 18 | "e": "f" 19 | }, 20 | "string": "Hello World" 21 | } -------------------------------------------------------------------------------- /mockwebserverplus/src/test/resources/fixtures/simple_with_delay.yaml: -------------------------------------------------------------------------------- 1 | statusCode : 200 2 | delay: 300 3 | headers: 4 | - 'Auth:auth' 5 | - 'key:value' 6 | body: '{result:{}}' -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | import groovy.io.FileType 2 | 3 | repositories { 4 | maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } 5 | } 6 | 7 | apply plugin: 'com.android.application' 8 | 9 | android { 10 | compileSdkVersion 25 11 | buildToolsVersion "25.0.2" 12 | 13 | defaultConfig { 14 | applicationId "com.orhanobut.sample" 15 | minSdkVersion 16 16 | targetSdkVersion 25 17 | versionCode 1 18 | versionName "1.0" 19 | } 20 | 21 | compileOptions { 22 | sourceCompatibility JavaVersion.VERSION_1_7 23 | targetCompatibility JavaVersion.VERSION_1_7 24 | } 25 | } 26 | 27 | task generateFixtures(group: 'fixtures') << { 28 | def directory = projectDir.path + '/src/test/java' 29 | new File(directory + '/fixtures').mkdir() 30 | def path = directory + "/fixtures/Fixtures.java" 31 | 32 | def builder = '' << '' 33 | builder.append("package fixtures;\n\n") 34 | builder.append("public class Fixtures {\n\n") 35 | builder.append(" private Fixtures() {\n") 36 | builder.append(" //no instance\n") 37 | builder.append(" }\n\n") 38 | 39 | def resources = android.sourceSets.test.resources.srcDirs.getAt(0) 40 | if (resources.size() > 0) { 41 | resources.eachDirMatch("fixtures") { dir -> 42 | def fixturesFile = dir 43 | fixturesFile.eachFile(FileType.FILES) { file -> 44 | if (file.name.endsWith(".yaml")) { 45 | String fileName = file.name.split('\\.')[0] 46 | builder.append(" public static final String ") 47 | .append(fileName.toUpperCase()) 48 | .append(" = ") 49 | .append('\"') 50 | .append(fileName) 51 | .append('\";\n') 52 | } 53 | } 54 | } 55 | } 56 | builder.append("}\n") 57 | 58 | new File(path).write(builder.toString()) 59 | } 60 | 61 | preBuild.dependsOn generateFixtures 62 | 63 | dependencies { 64 | testCompile 'junit:junit:4.12' 65 | testCompile 'org.assertj:assertj-core:2.4.0' 66 | testCompile 'org.mockito:mockito-core:1.9.5' 67 | testCompile 'com.squareup.okhttp3:okhttp:3.7.0' 68 | 69 | testCompile project(':mockwebserverplus') 70 | } 71 | 72 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /sample/src/test/java/com/orhanobut/sample/FooTest.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.sample; 2 | 3 | import com.orhanobut.mockwebserverplus.MockWebServerPlus; 4 | 5 | import org.junit.Rule; 6 | import org.junit.Test; 7 | 8 | import java.io.IOException; 9 | 10 | import fixtures.Fixtures; 11 | import okhttp3.OkHttpClient; 12 | import okhttp3.Request; 13 | import okhttp3.Response; 14 | 15 | import static org.junit.Assert.assertNotNull; 16 | 17 | public class FooTest { 18 | 19 | @Rule public MockWebServerPlus server = new MockWebServerPlus(); 20 | 21 | @Test public void testFoo() throws IOException { 22 | server.enqueue(Fixtures.SIMPLE); 23 | 24 | Request request = new Request.Builder() 25 | .url(server.url("/")) 26 | .get() 27 | .build(); 28 | 29 | OkHttpClient client = new OkHttpClient(); 30 | Response response = client.newCall(request).execute(); 31 | 32 | assertNotNull(response); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /sample/src/test/java/fixtures/Fixtures.java: -------------------------------------------------------------------------------- 1 | package fixtures; 2 | 3 | public class Fixtures { 4 | 5 | private Fixtures() { 6 | //no instance 7 | } 8 | 9 | public static final String SIMPLE = "simple"; 10 | } 11 | -------------------------------------------------------------------------------- /sample/src/test/resources/fixtures/simple.yaml: -------------------------------------------------------------------------------- 1 | statusCode : 200 2 | delay: 0 3 | headers: 4 | - 'Auth:auth' 5 | - 'key:value' 6 | body: > 7 | { 8 | "array": [ 9 | 1, 10 | 2, 11 | 3 12 | ], 13 | "boolean": true, 14 | "null": null, 15 | "number": 123, 16 | "object": { 17 | "a": "b", 18 | "c": "d", 19 | "e": "f" 20 | }, 21 | "string": "Hello World" 22 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':sample' 2 | include ':mockwebserverplus' 3 | --------------------------------------------------------------------------------