├── .github └── workflows │ └── maven.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── lombok.config ├── okhttppoc.iml ├── pom.xml ├── src ├── main │ ├── java │ │ └── com │ │ │ └── faisalkhatri │ │ │ └── okhttppoc │ │ │ ├── AuthenticationPojo.java │ │ │ ├── PostData.java │ │ │ └── TestListener.java │ └── resources │ │ └── log4j2.xml └── test │ └── java │ ├── com │ └── faisalkhatri │ │ └── okhttppoc │ │ ├── SetupConfig.java │ │ ├── TestAuthentication.java │ │ ├── TestDeleteRequests.java │ │ ├── TestGetRequestWithRestAssuredConfig.java │ │ ├── TestGetRequests.java │ │ ├── TestPatchRequests.java │ │ ├── TestPostRequest.java │ │ ├── TestPostRequestBuilderExample.java │ │ └── TestPutRequests.java │ └── data │ └── UserData.java └── testng.xml /.github/workflows/maven.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven 3 | 4 | name: Java CI with Maven 5 | 6 | on: 7 | push: 8 | branches: 9 | - master 10 | - issue-* 11 | 12 | jobs: 13 | build_and_test: 14 | name: Build and Test 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: checkout Git repository 19 | uses: actions/checkout@v2 20 | 21 | - name: Install Java and Maven 22 | uses: actions/setup-java@v2 23 | with: 24 | java-version: '15' 25 | distribution: 'adopt' 26 | cache: maven 27 | 28 | - name: Build the Project 29 | run: mvn clean install -DskipTests 30 | 31 | - name: Test Execution 32 | run: mvn org.jacoco:jacoco-maven-plugin:prepare-agent install -Pcoverage-per-test 33 | 34 | - name: Upload target folder 35 | uses: actions/upload-artifact@v2 36 | with: 37 | name: target 38 | path: | 39 | ${{ github.workspace }}/target 40 | ${{ github.workspace }}/reports 41 | code_analysis: 42 | name: Code Analysis 43 | needs: 44 | - build_and_test 45 | 46 | runs-on: ubuntu-latest 47 | 48 | steps: 49 | - name: checkout Git repository 50 | uses: actions/checkout@v2 51 | with: 52 | fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis 53 | 54 | - name: Install Java and Maven 55 | uses: actions/setup-java@v2 56 | with: 57 | java-version: '15' 58 | distribution: 'adopt' 59 | cache: maven 60 | 61 | - name: Cache SonarCloud packages 62 | uses: actions/cache@v2 63 | with: 64 | path: ~/.sonar/cache 65 | key: ${{ runner.os }}-sonar 66 | restore-keys: ${{ runner.os }}-sonar 67 | 68 | - name: Cache Maven packages 69 | uses: actions/cache@v2 70 | with: 71 | path: ~/.m2 72 | key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} 73 | restore-keys: ${{ runner.os }}-m2 74 | 75 | - name: Download target folder 76 | uses: actions/download-artifact@v2 77 | with: 78 | name: target 79 | 80 | - name: Sonar Code Analysis 81 | env: 82 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any 83 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 84 | SONAR_KEY: ${{ secrets.SONAR_KEY }} 85 | run: | 86 | mvn -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \ 87 | -Dsonar.projectKey=$SONAR_KEY 88 | - name: Test Report 89 | uses: dorny/test-reporter@v1 90 | if: success() || failure() 91 | with: 92 | name: Test Results 93 | path: ${{ github.workspace }}/target/surefire-reports/TEST-TestSuite.xml 94 | reporter: java-junit 95 | java-version: 11 96 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /test-output/ 3 | /settings/ 4 | /reports/ 5 | /logs/ 6 | /.settings/ 7 | /.classpath 8 | /.project 9 | /.idea/ 10 | /*.iml/ -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | mohammadfaisalkhatri@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /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 | 2 | ![Open Source Love](https://badges.frapsoft.com/os/v1/open-source.svg?v=103) 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | [![Github Actions Workflow](https://github.com/mfaisalkhatri/OkHttpRestAssuredExamples/actions/workflows/maven.yml/badge.svg)](https://github.com/mfaisalkhatri/OkHttpRestAssuredExamples/actions/workflows/maven.yml) 5 | [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=mfaisalkhatri_OkHttpRestAssuredExamples&metric=sqale_rating)](https://sonarcloud.io/summary/new_code?id=mfaisalkhatri_OkHttpRestAssuredExamples) 6 | [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=mfaisalkhatri_OkHttpRestAssuredExamples&metric=coverage)](https://sonarcloud.io/summary/new_code?id=mfaisalkhatri_OkHttpRestAssuredExamples) 7 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=mfaisalkhatri_OkHttpRestAssuredExamples&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=mfaisalkhatri_OkHttpRestAssuredExamples) 8 | [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=mfaisalkhatri_OkHttpRestAssuredExamples&metric=reliability_rating)](https://sonarcloud.io/summary/new_code?id=mfaisalkhatri_OkHttpRestAssuredExamples) 9 | 10 | 11 | ## Don't forget to give a :star: to make the project popular. 12 | 13 | ## :question: What is this Repository about? 14 | 15 | This project is the outcome of my self-learning the API Testing Automation frameworks - Rest-assured and OkHttp. 16 | I heard a lot about Rest-Assured and OkHttp and how it made the QA's life easier by helping them to run all the tedious API tests in an efficient way. 17 | 18 | Hence, I started learning about these frameworks and have documented all my learnings in this repository. 19 | 20 | Checkout my blog [API Testing using RestAssured and OkHttp][blog] where I talk about these frameworks in details 21 | and which one to choose for testing your APIs. 22 | 23 | To get a better understanding on API Testing, check [What is API Testing?][blog_apitesting] 24 | 25 | ## Details about this Project: 26 | 27 | - This repo contains example codes of API Tests using Rest-Assured and OkHttp. 28 | - Hamcrest Matchers and TestNG asserts are used for assertions. 29 | - TestNG Listeners are used to capture the events in log. 30 | - Log4j is used to capture logs. 31 | - Lombok has been used to generate Getter and Setters automatically for post body requests. 32 | - Rest APIs on https://reqres.in/ have been used for testing. 33 | 34 | ## :question: Need Assistance? 35 | 36 | - Discuss your queries by writing to me at [mohammadfaisalkhatri@gmail.com][mail] or you can ping me on the following social media sites: 37 | - Twitter: [mfaisal_khatri][twitter] 38 | - LinkedIn: [Mohammad Faisal Khatri][linkedin] 39 | - Contact me for 1:1 trainings related to Test Automation. 40 | 41 | ## :thought_balloon: Checkout the blogs related to Testing on my [website][] 42 | 43 | [mail]: mohammadfaisalkhatri@gmail.com 44 | [linkedin]: https://www.linkedin.com/in/faisalkhatri/ 45 | [twitter]: https://twitter.com/mfaisal_khatri 46 | [website]: https://mfaisalkhatri.github.io 47 | [blog]: https://mfaisalkhatri.github.io/2020/05/29/restassuredokhttp/ 48 | [blog_apitesting]: https://mfaisalkhatri.github.io/2020/08/08/apitesting/ -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | config.stopBubbling = true 2 | lombok.addLombokGeneratedAnnotation = true -------------------------------------------------------------------------------- /okhttppoc.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 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 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 4.0.0 7 | 8 | com.faisalkhatri 9 | okhttppoc 10 | 0.0.1-SNAPSHOT 11 | 12 | okhttppoc 13 | https://mfaisalkhatri.github.io 14 | 15 | 16 | UTF-8 17 | 3.8.1 18 | 3.0.0-M5 19 | 15 20 | UTF-8 21 | testng.xml 22 | -Dfile.encoding=UTF-8 -Xdebug -Xnoagent 23 | https://sonarcloud.io 24 | ${project.basedir}/target/reports/jacoco.exec 25 | mfaisalkhatri 26 | ${project.basedir}/reports/jacoco.exec 27 | ${project.basedir}/target/site/jacoco/jacoco.xml 28 | 29 | 15 30 | 0.8.7 31 | 5.14.0.18788 32 | target/dependency/*.jar 33 | 3.2.0 34 | 35 | 36 | 37 | 38 | 39 | org.testng 40 | testng 41 | 7.5 42 | 43 | 44 | 45 | com.squareup.okhttp3 46 | okhttp 47 | 4.9.3 48 | 49 | 50 | io.rest-assured 51 | rest-assured 52 | 4.4.0 53 | 54 | 55 | 56 | org.hamcrest 57 | hamcrest-all 58 | 1.3 59 | 60 | 61 | 62 | org.apache.logging.log4j 63 | log4j-core 64 | 2.17.1 65 | 66 | 67 | 68 | org.apache.logging.log4j 69 | log4j-api 70 | 2.17.1 71 | 72 | 73 | 74 | com.googlecode.json-simple 75 | json-simple 76 | 1.1.1 77 | 78 | 79 | 80 | org.projectlombok 81 | lombok 82 | 1.18.22 83 | provided 84 | 85 | 86 | 87 | com.fasterxml.jackson.core 88 | jackson-databind 89 | 2.13.4.1 90 | 91 | 92 | 93 | org.json 94 | json 95 | 20211205 96 | 97 | 98 | com.github.javafaker 99 | javafaker 100 | 1.0.2 101 | 102 | 103 | 104 | 105 | 106 | org.apache.maven.plugins 107 | maven-compiler-plugin 108 | ${maven.compiler.version} 109 | 110 | ${java.release.version} 111 | ${maven.source.encoding} 112 | true 113 | 114 | 115 | 116 | org.apache.maven.plugins 117 | maven-surefire-plugin 118 | ${surefire-version} 119 | 120 | 121 | 122 | test 123 | 124 | 125 | 126 | 127 | false 128 | 129 | 130 | usedefaultlisteners 131 | false 132 | 133 | 134 | 135 | ${suite-xml} 136 | 137 | ${argLine} 138 | 139 | 140 | 141 | org.apache.maven.plugins 142 | maven-dependency-plugin 143 | ${maven.dependency.version} 144 | 145 | 146 | copy-dependencies 147 | package 148 | 149 | copy-dependencies 150 | 151 | 152 | lombok 153 | 154 | 155 | 156 | 157 | 158 | org.sonarsource.scanner.maven 159 | sonar-maven-plugin 160 | 3.9.1.2184 161 | 162 | 163 | org.jacoco 164 | jacoco-maven-plugin 165 | ${jacoco.version} 166 | 167 | 168 | prepare-agent 169 | 170 | prepare-agent 171 | 172 | 173 | ${sonar.report} 174 | surefireArgLine 175 | 176 | 177 | 178 | report 179 | test 180 | 181 | report 182 | 183 | 184 | ${sonar.report} 185 | ${project.reporting.outputDirectory}/jacoco 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | coverage-per-test 195 | 196 | 197 | 198 | org.apache.maven.plugins 199 | maven-surefire-plugin 200 | ${surefire-version} 201 | 202 | 203 | 204 | test 205 | 206 | 207 | 208 | 209 | 210 | ${suite-xml} 211 | 212 | ${argLine} ${surefireArgLine} 213 | 214 | 215 | 216 | 217 | 218 | 219 | org.sonarsource.java 220 | sonar-jacoco-listeners 221 | ${sonar.version} 222 | test 223 | 224 | 225 | 226 | 227 | -------------------------------------------------------------------------------- /src/main/java/com/faisalkhatri/okhttppoc/AuthenticationPojo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import lombok.Data; 20 | 21 | /** 22 | * @author Faisal Khatri 23 | * @since Aug 2, 2020 24 | * 25 | */ 26 | @Data 27 | public class AuthenticationPojo { 28 | 29 | private String email; 30 | private String password; 31 | 32 | /** 33 | *@author Faisal Khatri 34 | *@param email 35 | *@param password 36 | */ 37 | public AuthenticationPojo (String email, String password) { 38 | this.email = email; 39 | this.password = password; 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/com/faisalkhatri/okhttppoc/PostData.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import lombok.Getter; 20 | import lombok.Setter; 21 | 22 | /** 23 | * @since Mar 7, 2020 24 | * 25 | */ 26 | @Getter 27 | @Setter 28 | public class PostData { 29 | 30 | private final String name; 31 | private final String job; 32 | 33 | /** 34 | * 35 | * @author Faisal Khatri 36 | * @param name 37 | * @param job 38 | */ 39 | public PostData (final String name, final String job) { 40 | this.name = name; 41 | this.job = job; 42 | 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/main/java/com/faisalkhatri/okhttppoc/TestListener.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static org.apache.commons.lang3.StringUtils.repeat; 20 | 21 | import org.apache.logging.log4j.LogManager; 22 | import org.apache.logging.log4j.Logger; 23 | import org.testng.ITestContext; 24 | import org.testng.ITestListener; 25 | import org.testng.ITestResult; 26 | 27 | /** 28 | * @since Mar 8, 2020 29 | */ 30 | public class TestListener implements ITestListener { 31 | 32 | Logger log = LogManager.getLogger (TestListener.class); 33 | 34 | private void logMessage (final String message) { 35 | this.log.info ("\n"); 36 | this.log.info (repeat ("=", 75)); 37 | this.log.info (message); 38 | this.log.info (repeat ("=", 75)); 39 | this.log.info ("\n"); 40 | } 41 | 42 | @Override 43 | public void onTestStart (final ITestResult result) { 44 | logMessage ("Test Execution Started...." + result.getName ()); 45 | } 46 | 47 | @Override 48 | public void onTestSuccess (final ITestResult result) { 49 | logMessage ("Test Passed Successfully." + result.getName ()); 50 | 51 | } 52 | 53 | @Override 54 | public void onTestFailure (final ITestResult result) { 55 | logMessage ("Test Failed!!!!" + result.getName ()); 56 | } 57 | 58 | @Override 59 | public void onFinish (final ITestContext context) { 60 | logMessage ("Test Execution Completed Successfully for all tests!!" + context.getSuite () 61 | .getAllMethods ()); 62 | 63 | } 64 | 65 | } -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/SetupConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import io.restassured.RestAssured; 20 | import io.restassured.builder.RequestSpecBuilder; 21 | import io.restassured.builder.ResponseSpecBuilder; 22 | import io.restassured.filter.log.RequestLoggingFilter; 23 | import io.restassured.filter.log.ResponseLoggingFilter; 24 | import io.restassured.specification.RequestSpecification; 25 | import io.restassured.specification.ResponseSpecification; 26 | import org.testng.annotations.BeforeClass; 27 | 28 | import static org.hamcrest.Matchers.lessThan; 29 | 30 | public class SetupConfig { 31 | 32 | @BeforeClass 33 | public void setup() { 34 | RestAssured.baseURI = "https://reqres.in/"; 35 | 36 | RequestSpecification request = new RequestSpecBuilder() 37 | .addHeader("Content-Type", "application/json") 38 | .addHeader("Accept", "application/json") 39 | .addFilter(new RequestLoggingFilter()) 40 | .addFilter(new ResponseLoggingFilter()) 41 | .build(); 42 | 43 | ResponseSpecification response = new ResponseSpecBuilder() 44 | .expectResponseTime(lessThan(5000L)) 45 | .build(); 46 | 47 | RestAssured.requestSpecification = request; 48 | RestAssured.responseSpecification = response; 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestAuthentication.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.hamcrest.Matchers.notNullValue; 21 | 22 | import java.util.ArrayList; 23 | import java.util.HashMap; 24 | import java.util.Iterator; 25 | import java.util.List; 26 | import java.util.Map; 27 | 28 | import io.restassured.http.ContentType; 29 | import org.json.JSONObject; 30 | import org.testng.annotations.DataProvider; 31 | import org.testng.annotations.Test; 32 | 33 | /** 34 | * @author Faisal Khatri 35 | * @since Aug 2, 2020 36 | */ 37 | public class TestAuthentication { 38 | 39 | private static final String URL = "https://reqres.in"; 40 | 41 | /** 42 | * @author Faisal Khatri 43 | * @since Aug 2, 2020 44 | * @return test data 45 | */ 46 | @DataProvider 47 | public Iterator getAuthenticationData () { 48 | final List getTestData = new ArrayList<> (); 49 | getTestData.add (new Object [] { "eve.holt@reqres.in", "pistol" }); 50 | return getTestData.iterator (); 51 | } 52 | 53 | /** 54 | * @author Faisal Khatri 55 | * @since Aug 2, 2020 56 | * @param email 57 | * @param password 58 | */ 59 | @Test (dataProvider = "getAuthenticationData") 60 | public void testAuthenticationToken (String email, String password) { 61 | final AuthenticationPojo requestBody = new AuthenticationPojo (email, password); 62 | 63 | given ().contentType (ContentType.JSON) 64 | .body (requestBody) 65 | .when () 66 | .log () 67 | .all () 68 | .post (URL + "/api/register") 69 | .then () 70 | .assertThat () 71 | .statusCode (200) 72 | .log () 73 | .all () 74 | .body ("id", notNullValue ()) 75 | .and () 76 | .body ("token", notNullValue ()); 77 | 78 | } 79 | 80 | /** 81 | * @author Faisal Khatri 82 | * @since Aug 2, 2020 83 | * @param email 84 | * @param password 85 | * @return auth details 86 | */ 87 | public static Map getToken (String email, String password) { 88 | final AuthenticationPojo requestBody = new AuthenticationPojo (email, password); 89 | final String response = given ().contentType (ContentType.JSON) 90 | .body (requestBody) 91 | .when () 92 | .log () 93 | .all () 94 | .post (URL + "/api/register") 95 | .then () 96 | .assertThat () 97 | .statusCode (200) 98 | .log () 99 | .all () 100 | .body ("id", notNullValue ()) 101 | .and () 102 | .body ("token", notNullValue ()) 103 | .and () 104 | .extract () 105 | .response () 106 | .asString (); 107 | 108 | final JSONObject responseObject = new JSONObject (response); 109 | final Map responseMap = new HashMap<> (); 110 | responseMap.put ("id", responseObject.getInt ("id")); 111 | responseMap.put ("token", responseObject.getString ("token")); 112 | return responseMap; 113 | } 114 | 115 | /** 116 | * @author Faisal Khatri 117 | * @since Aug 2, 2020 118 | * @param email 119 | * @param password 120 | */ 121 | @Test (dataProvider = "getAuthenticationData") 122 | public void testAuthToken (String email, String password) { 123 | System.out.println ("Token is" + getToken (email, password).get ("token") 124 | .toString ()); 125 | 126 | } 127 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestDeleteRequests.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.testng.Assert.assertEquals; 21 | 22 | import java.io.IOException; 23 | import java.util.ArrayList; 24 | import java.util.Iterator; 25 | import java.util.List; 26 | 27 | import okhttp3.OkHttpClient; 28 | import okhttp3.Request; 29 | import okhttp3.Response; 30 | import org.testng.annotations.DataProvider; 31 | import org.testng.annotations.Test; 32 | 33 | /** 34 | * @since Mar 8, 2020 35 | */ 36 | public class TestDeleteRequests { 37 | 38 | private static final String URL = "https://reqres.in/api/users/"; 39 | 40 | /** 41 | * @since Mar 8, 2020 42 | * @return deleteUserData using okhttp 43 | */ 44 | @DataProvider (name = "deleteUserOkHttp") 45 | public Iterator deleteokHttpUsers () { 46 | final List deleteData = new ArrayList<> (); 47 | deleteData.add (new Object [] { 8 }); 48 | return deleteData.iterator (); 49 | } 50 | 51 | /** 52 | * @since Mar 8, 2020 53 | * @return deleteUserData using rest assured 54 | */ 55 | @DataProvider (name = "deleteUserRestAssured") 56 | public Iterator deleteRestUsers () { 57 | final List deleteData = new ArrayList<> (); 58 | deleteData.add (new Object [] { 2 }); 59 | return deleteData.iterator (); 60 | } 61 | 62 | /** 63 | * Executing delete request using okhttp 64 | * 65 | * @since Mar 8, 2020 66 | * @param userId 67 | * @throws IOException 68 | */ 69 | @Test (dataProvider = "deleteUserOkHttp", groups = "DeleteTests") 70 | public void testDeleteUsingOkHttp (final int userId) throws IOException { 71 | final OkHttpClient client = new OkHttpClient (); 72 | final Request request = new Request.Builder ().url (URL + userId) 73 | .delete () 74 | .build (); 75 | 76 | final Response response = client.newCall (request) 77 | .execute (); 78 | final int statusCode = response.code (); 79 | assertEquals (statusCode, 204); 80 | } 81 | 82 | /** 83 | * Executing delete requests using Rest-assured 84 | * 85 | * @since Mar 08, 2020 86 | * @param userId 87 | */ 88 | @Test (dataProvider = "deleteUserRestAssured", groups = "DeleteTests") 89 | public void testDeleUsingRestAsured (final int userId) { 90 | given ().when () 91 | .delete (URL + userId) 92 | .then () 93 | .assertThat () 94 | .statusCode (204); 95 | } 96 | 97 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestGetRequestWithRestAssuredConfig.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import org.testng.annotations.Test; 20 | 21 | import static io.restassured.RestAssured.given; 22 | import static org.hamcrest.Matchers.equalTo; 23 | 24 | public class TestGetRequestWithRestAssuredConfig extends SetupConfig { 25 | 26 | @Test(groups = "GetTests") 27 | public void testGetRequestwithRestAssured() { 28 | given() 29 | .when() 30 | .get("/api/users/2") 31 | .then() 32 | .statusCode(200) 33 | .and() 34 | .assertThat() 35 | .body("data.first_name", equalTo("Janet")); 36 | } 37 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestGetRequests.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.hamcrest.Matchers.equalTo; 21 | import static org.junit.Assert.assertThat; 22 | import static org.testng.Assert.assertEquals; 23 | 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.Iterator; 27 | import java.util.List; 28 | 29 | import okhttp3.HttpUrl; 30 | import okhttp3.OkHttpClient; 31 | import okhttp3.Request; 32 | import okhttp3.Response; 33 | import org.apache.logging.log4j.LogManager; 34 | import org.apache.logging.log4j.Logger; 35 | import org.json.JSONObject; 36 | import org.testng.annotations.DataProvider; 37 | import org.testng.annotations.Test; 38 | 39 | /** 40 | * @since Mar 7, 2020 41 | */ 42 | public class TestGetRequests { 43 | 44 | Logger log = LogManager.getLogger (TestGetRequests.class); 45 | private static final String URL = "https://reqres.in/api/users/"; 46 | 47 | /** 48 | * @since Mar 7, 2020 49 | * @return getUserData 50 | */ 51 | @DataProvider (name = "getUserData") 52 | public Iterator getUsers () { 53 | final List getData = new ArrayList<> (); 54 | getData.add (new Object [] { 2 }); 55 | return getData.iterator (); 56 | } 57 | 58 | /** 59 | * Executing get request using okhttp 60 | * 61 | * @param userId 62 | * @since Mar 7, 2020 63 | * @throws IOException 64 | */ 65 | @Test (dataProvider = "getUserData", groups = "GetTests") 66 | public void testGetRequestWithOkHttp (final int userId) throws IOException { 67 | final OkHttpClient client = new OkHttpClient (); 68 | final Request request = new Request.Builder ().url (URL + userId) 69 | .get () 70 | .build (); 71 | 72 | final Response response = client.newCall (request) 73 | .execute (); 74 | final String responseBody = response.body () 75 | .string (); 76 | final int statusCode = response.code (); 77 | this.log.info (responseBody); 78 | 79 | assertEquals (statusCode, 200); 80 | 81 | final JSONObject jsonResponse = new JSONObject (responseBody); 82 | final int id = jsonResponse.getJSONObject ("data") 83 | .getInt ("id"); 84 | assertThat (id, equalTo (userId)); 85 | } 86 | 87 | /** 88 | * Executing get requests using Rest-assured 89 | * 90 | * @param userId 91 | * @since Mar 7, 2020 92 | */ 93 | @Test (dataProvider = "getUserData", groups = "GetTests") 94 | public void testGetRequestWithRestAssured (final int userId) { 95 | given ().when () 96 | .get (URL + userId) 97 | .then () 98 | .statusCode (200) 99 | .and () 100 | .assertThat () 101 | .body ("data.id", equalTo (userId)); 102 | 103 | final int statusCode = given ().when () 104 | .get (URL + userId) 105 | .statusCode (); 106 | this.log.info (statusCode); 107 | 108 | final String responseBody = given ().when () 109 | .get (URL + userId) 110 | .getBody () 111 | .asString (); 112 | this.log.info (responseBody); 113 | } 114 | 115 | /** 116 | * @since Mar 7, 2020 117 | * @param userPage 118 | */ 119 | @Test (dataProvider = "getUserData", groups = "GetTests") 120 | public void testGetRequestWithQueryParamWithRestAssured (final int userPage) { 121 | given ().when () 122 | .queryParam ("page", userPage) 123 | .get (URL) 124 | .then () 125 | .statusCode (200) 126 | .and () 127 | .assertThat () 128 | .body ("page", equalTo (userPage)); 129 | 130 | final String responseBody = given ().when () 131 | .queryParam ("page", userPage) 132 | .get (URL) 133 | .getBody () 134 | .asString (); 135 | this.log.info (responseBody); 136 | } 137 | 138 | /** 139 | * @since Mar 7, 2020 140 | * @param userPage 141 | * @throws IOException 142 | */ 143 | @Test (dataProvider = "getUserData", groups = "GetTests") 144 | public void testGetRequestWithQueryParamOkHttp (final int userPage) throws IOException { 145 | final OkHttpClient client = new OkHttpClient (); 146 | final HttpUrl.Builder urlBuilder = HttpUrl.parse (URL) 147 | .newBuilder (); 148 | urlBuilder.addQueryParameter ("page", String.valueOf (userPage)); 149 | 150 | final String currentUrl = urlBuilder.build () 151 | .toString (); 152 | final Request request = new Request.Builder ().url (currentUrl) 153 | .build (); 154 | final Response response = client.newCall (request) 155 | .execute (); 156 | final String responseBody = response.body () 157 | .string (); 158 | final int statusCode = response.code (); 159 | this.log.info (statusCode); 160 | this.log.info (responseBody); 161 | assertEquals (statusCode, 200); 162 | final JSONObject jsonResponse = new JSONObject (responseBody); 163 | assertThat (jsonResponse.getInt ("page"), equalTo (userPage)); 164 | final String firstName = jsonResponse.getJSONArray ("data") 165 | .getJSONObject (0) 166 | .getString ("first_name"); 167 | assertThat (firstName, equalTo ("Michael")); 168 | 169 | } 170 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestPatchRequests.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.hamcrest.Matchers.equalTo; 21 | import static org.junit.Assert.assertThat; 22 | import static org.testng.Assert.assertEquals; 23 | 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.Iterator; 27 | import java.util.List; 28 | 29 | import io.restassured.http.ContentType; 30 | import okhttp3.MediaType; 31 | import okhttp3.OkHttpClient; 32 | import okhttp3.Request; 33 | import okhttp3.RequestBody; 34 | import okhttp3.Response; 35 | import org.apache.logging.log4j.LogManager; 36 | import org.apache.logging.log4j.Logger; 37 | import org.json.JSONObject; 38 | import org.testng.annotations.DataProvider; 39 | import org.testng.annotations.Test; 40 | 41 | /** 42 | * @since Mar 8, 2020 43 | */ 44 | public class TestPatchRequests { 45 | 46 | Logger log = LogManager.getLogger (TestPatchRequests.class); 47 | private static final String URL = "https://reqres.in"; 48 | 49 | /** 50 | * @since Mar 8, 2020 51 | * @return putData 52 | */ 53 | @DataProvider (name = "patchData") 54 | public Iterator patchData () { 55 | final List patchData = new ArrayList<> (); 56 | patchData.add (new Object [] { 2, "Michael", "QA Lead" }); 57 | patchData.add (new Object [] { 958, "Yuan", "Project Architect" }); 58 | return patchData.iterator (); 59 | } 60 | 61 | /** 62 | * Executing Put Request using Rest Assured. 63 | * 64 | * @since Mar 8, 2020 65 | * @param id 66 | * @param name 67 | * @param job 68 | */ 69 | @Test (dataProvider = "patchData", groups = "PatchTests") 70 | public void testPatchWithRestAssured (final int id, final String name, final String job) { 71 | 72 | final PostData postData = new PostData (name, job); 73 | final String response = given ().contentType (ContentType.JSON) 74 | .body (postData) 75 | .when () 76 | .patch (URL + "/api/users/" + id) 77 | .then () 78 | .assertThat () 79 | .statusCode (200) 80 | .and () 81 | .assertThat () 82 | .body ("name", equalTo (name)) 83 | .and () 84 | .assertThat () 85 | .body ("job", equalTo (job)) 86 | .and () 87 | .extract () 88 | .response () 89 | .body () 90 | .asString (); 91 | 92 | this.log.info (response); 93 | 94 | } 95 | 96 | /** 97 | * Executing Put Request using OkHttp 98 | * 99 | * @since Mar 8, 2020 100 | * @param id 101 | * @param name 102 | * @param job 103 | * @throws IOException 104 | */ 105 | @Test (dataProvider = "patchData", groups = "PatchTests") 106 | public void testPatchWithOkHttp (final int id, final String name, final String job) throws IOException { 107 | final MediaType JSON = MediaType.parse ("application/json; charset=utf-8"); 108 | final PostData postData = new PostData (name, job); 109 | 110 | final OkHttpClient client = new OkHttpClient (); 111 | 112 | final JSONObject json = new JSONObject (postData); 113 | final RequestBody requestBody = RequestBody.create (json.toString (), JSON); 114 | 115 | final Request request = new Request.Builder ().url (URL + "/api/users/" + id) 116 | .addHeader ("Content-Type", "application/json;charset=utf-8") 117 | .patch (requestBody) 118 | .build (); 119 | 120 | final Response response = client.newCall (request) 121 | .execute (); 122 | 123 | final int statusCode = response.code (); 124 | this.log.info (statusCode); 125 | 126 | final String responseBody = response.body () 127 | .string (); 128 | 129 | this.log.info (responseBody); 130 | 131 | final JSONObject jsonResponse = new JSONObject (responseBody); 132 | assertEquals (statusCode, 200); 133 | assertThat (jsonResponse.getString ("name"), equalTo (name)); 134 | assertThat (jsonResponse.getString ("job"), equalTo (job)); 135 | 136 | } 137 | 138 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestPostRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.hamcrest.Matchers.equalTo; 21 | import static org.hamcrest.Matchers.notNullValue; 22 | import static org.junit.Assert.assertThat; 23 | import static org.testng.Assert.assertEquals; 24 | 25 | import java.io.IOException; 26 | import java.util.ArrayList; 27 | import java.util.Iterator; 28 | import java.util.List; 29 | 30 | import io.restassured.http.ContentType; 31 | import okhttp3.FormBody; 32 | import okhttp3.MediaType; 33 | import okhttp3.OkHttpClient; 34 | import okhttp3.Request; 35 | import okhttp3.RequestBody; 36 | import okhttp3.Response; 37 | import org.apache.logging.log4j.LogManager; 38 | import org.apache.logging.log4j.Logger; 39 | import org.json.JSONObject; 40 | import org.testng.annotations.DataProvider; 41 | import org.testng.annotations.Test; 42 | 43 | /** 44 | * @since Mar 7, 2020 45 | */ 46 | public class TestPostRequest { 47 | 48 | Logger log = LogManager.getLogger (TestPostRequest.class); 49 | private static final String URL = "https://reqres.in"; 50 | 51 | /** 52 | * @since Mar 7, 2020 53 | * @return postData 54 | */ 55 | @DataProvider (name = "postData") 56 | public Iterator postData () { 57 | final List postData = new ArrayList<> (); 58 | postData.add (new Object [] { "Rahul", "QA" }); 59 | postData.add (new Object [] { "Jane", "Sr.Dev" }); 60 | postData.add (new Object [] { "Albert", "Dev" }); 61 | postData.add (new Object [] { "Johnny", "Project Manager" }); 62 | return postData.iterator (); 63 | } 64 | 65 | /** 66 | * @param name 67 | * @param job 68 | * @since Mar 7, 2020 69 | */ 70 | @Test (dataProvider = "postData", groups = "PostTests") 71 | public void testPostWithRestAssured (final String name, final String job) { 72 | final PostData postData = new PostData (name, job); 73 | final String response = given ().contentType (ContentType.JSON) 74 | .body (postData) 75 | .when () 76 | .post (URL + "/api/users") 77 | .then () 78 | .assertThat () 79 | .statusCode (201) 80 | .and () 81 | .assertThat () 82 | .body ("name", equalTo (name)) 83 | .and () 84 | .assertThat () 85 | .body ("job", equalTo (job)) 86 | .and () 87 | .assertThat () 88 | .body ("id", notNullValue ()) 89 | .and () 90 | .extract () 91 | .response () 92 | .body () 93 | .asString (); 94 | 95 | this.log.info (response); 96 | 97 | } 98 | 99 | /** 100 | * @since Mar 7, 2020 101 | * @param name 102 | * @param job 103 | * @throws IOException 104 | */ 105 | @Test (dataProvider = "postData", groups = "PostTests") 106 | public void testPostWithOkHttp (final String name, final String job) throws IOException { 107 | final MediaType JSON = MediaType.parse ("application/json; charset=utf-8"); 108 | final PostData postData = new PostData (name, job); 109 | 110 | final OkHttpClient client = new OkHttpClient (); 111 | 112 | final JSONObject json = new JSONObject (postData); 113 | final RequestBody requestBody = RequestBody.create (json.toString (), JSON); 114 | 115 | final Request request = new Request.Builder ().url (URL + "/api/users") 116 | .addHeader ("Content-Type", "application/json;charset=utf-8") 117 | .post (requestBody) 118 | .build (); 119 | 120 | final Response response = client.newCall (request) 121 | .execute (); 122 | 123 | final int statusCode = response.code (); 124 | this.log.info (statusCode); 125 | 126 | final String responseBody = response.body () 127 | .string (); 128 | 129 | this.log.info (responseBody); 130 | 131 | final JSONObject jsonResponse = new JSONObject (responseBody); 132 | assertEquals (statusCode, 201); 133 | assertThat (jsonResponse.getString ("name"), equalTo (name)); 134 | assertThat (jsonResponse.getString ("job"), equalTo (job)); 135 | assertThat (jsonResponse.getString ("id"), notNullValue ()); 136 | 137 | } 138 | 139 | /** 140 | * @since Mar 7, 2020 141 | * @param name 142 | * @param job 143 | * @throws IOException 144 | */ 145 | @Test (dataProvider = "postData", groups = "PostTests") 146 | public void testPostwithOkHttpForm (final String name, final String job) throws IOException { 147 | final OkHttpClient client = new OkHttpClient (); 148 | final RequestBody formBody = new FormBody.Builder ().add ("name", name) 149 | .add ("job", job) 150 | .build (); 151 | final Request request = new Request.Builder ().url (URL + "/api/users") 152 | .post (formBody) 153 | .build (); 154 | 155 | final Response response = client.newCall (request) 156 | .execute (); 157 | 158 | final int statusCode = response.code (); 159 | this.log.info (statusCode); 160 | 161 | final String responseBody = response.body () 162 | .string (); 163 | 164 | this.log.info (responseBody); 165 | 166 | final JSONObject jsonResponse = new JSONObject (responseBody); 167 | assertEquals (statusCode, 201); 168 | assertThat (jsonResponse.getString ("name"), equalTo (name)); 169 | assertThat (jsonResponse.getString ("job"), equalTo (job)); 170 | assertThat (jsonResponse.getString ("id"), notNullValue ()); 171 | 172 | } 173 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestPostRequestBuilderExample.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.hamcrest.Matchers.equalTo; 21 | 22 | import com.github.javafaker.Faker; 23 | import data.UserData; 24 | import org.testng.annotations.Test; 25 | 26 | 27 | public class TestPostRequestBuilderExample extends SetupConfig { 28 | 29 | 30 | @Test 31 | public void postUsingBuilderPatternWithRestAssured() { 32 | 33 | UserData userData = userDataBuilder(); 34 | given() 35 | .body(userData) 36 | .when() 37 | .post("/api/users") 38 | .then() 39 | .statusCode(201) 40 | .and() 41 | .assertThat() 42 | .body("name", equalTo(userData.getName())) 43 | .body("job", equalTo(userData.getJob())); 44 | 45 | } 46 | 47 | private UserData userDataBuilder() { 48 | Faker faker = Faker.instance(); 49 | return UserData.builder().name(faker.name().firstName()).job(faker.company().profession()) 50 | .build(); 51 | } 52 | 53 | 54 | } -------------------------------------------------------------------------------- /src/test/java/com/faisalkhatri/okhttppoc/TestPutRequests.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package com.faisalkhatri.okhttppoc; 18 | 19 | import static io.restassured.RestAssured.given; 20 | import static org.hamcrest.Matchers.equalTo; 21 | import static org.junit.Assert.assertThat; 22 | import static org.testng.Assert.assertEquals; 23 | 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.Iterator; 27 | import java.util.List; 28 | 29 | import io.restassured.http.ContentType; 30 | import okhttp3.MediaType; 31 | import okhttp3.OkHttpClient; 32 | import okhttp3.Request; 33 | import okhttp3.RequestBody; 34 | import okhttp3.Response; 35 | import org.apache.logging.log4j.LogManager; 36 | import org.apache.logging.log4j.Logger; 37 | import org.json.JSONObject; 38 | import org.testng.annotations.DataProvider; 39 | import org.testng.annotations.Test; 40 | 41 | /** 42 | * @since Mar 8, 2020 43 | */ 44 | public class TestPutRequests { 45 | 46 | Logger log = LogManager.getLogger (TestPutRequests.class); 47 | private static final String URL = "https://reqres.in"; 48 | 49 | /** 50 | * @since Mar 8, 2020 51 | * @return putData 52 | */ 53 | @DataProvider (name = "putData") 54 | public Iterator putData () { 55 | final List putData = new ArrayList<> (); 56 | putData.add (new Object [] { 2, "Michael", "QA Lead" }); 57 | putData.add (new Object [] { 958, "Yuan", "Project Architect" }); 58 | return putData.iterator (); 59 | } 60 | 61 | /** 62 | * Executing Put Request using Rest Assured. 63 | * 64 | * @since Mar 8, 2020 65 | * @param id 66 | * @param name 67 | * @param job 68 | */ 69 | @Test (dataProvider = "putData", groups = "PutTests") 70 | public void testPutWithRestAssured (final int id, final String name, final String job) { 71 | 72 | final PostData postData = new PostData (name, job); 73 | final String response = given ().contentType (ContentType.JSON) 74 | .body (postData) 75 | .when () 76 | .put (URL + "/api/users/" + id) 77 | .then () 78 | .assertThat () 79 | .statusCode (200) 80 | .and () 81 | .assertThat () 82 | .body ("name", equalTo (name)) 83 | .and () 84 | .assertThat () 85 | .body ("job", equalTo (job)) 86 | .and () 87 | .extract () 88 | .response () 89 | .body () 90 | .asString (); 91 | 92 | this.log.info (response); 93 | 94 | } 95 | 96 | /** 97 | * Executing Put Request using OkHttp 98 | * 99 | * @since Mar 8, 2020 100 | * @param id 101 | * @param name 102 | * @param job 103 | * @throws IOException 104 | */ 105 | @Test (dataProvider = "putData", groups = "PutTests") 106 | public void testPutWithOkHttp (final int id, final String name, final String job) throws IOException { 107 | final MediaType JSON = MediaType.parse ("application/json; charset=utf-8"); 108 | final PostData postData = new PostData (name, job); 109 | 110 | final OkHttpClient client = new OkHttpClient (); 111 | 112 | final JSONObject json = new JSONObject (postData); 113 | final RequestBody requestBody = RequestBody.create (json.toString (), JSON); 114 | 115 | final Request request = new Request.Builder ().url (URL + "/api/users/" + id) 116 | .addHeader ("Content-Type", "application/json;charset=utf-8") 117 | .put (requestBody) 118 | .build (); 119 | 120 | final Response response = client.newCall (request) 121 | .execute (); 122 | 123 | final int statusCode = response.code (); 124 | this.log.info (statusCode); 125 | 126 | final String responseBody = response.body () 127 | .string (); 128 | 129 | this.log.info (responseBody); 130 | 131 | final JSONObject jsonResponse = new JSONObject (responseBody); 132 | assertEquals (statusCode, 200); 133 | assertThat (jsonResponse.getString ("name"), equalTo (name)); 134 | assertThat (jsonResponse.getString ("job"), equalTo (job)); 135 | 136 | } 137 | 138 | } -------------------------------------------------------------------------------- /src/test/java/data/UserData.java: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2022 Mohammad Faisal Khatri 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package data; 18 | 19 | import lombok.Builder; 20 | import lombok.Data; 21 | 22 | @Data 23 | @Builder 24 | public class UserData { 25 | 26 | private String name; 27 | private String job; 28 | } -------------------------------------------------------------------------------- /testng.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 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 | --------------------------------------------------------------------------------