├── .gitignore
├── ReadMe.md
├── Tests.xml
├── build.gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
└── test
├── java
├── Chapters
│ ├── Chapter01
│ │ ├── Chapter01.md
│ │ ├── Chapter01GradleConfig.md
│ │ └── FirstChapterTests.java
│ ├── Chapter02
│ │ ├── Chapter02.md
│ │ └── SecondChapterTests.java
│ ├── Chapter03
│ │ ├── Chapter03.md
│ │ └── ThirdChapterTests.java
│ ├── Chapter04
│ │ ├── Chapter04.md
│ │ └── FourthChapterTests.java
│ └── Chapter05
│ │ ├── Chapter05.md
│ │ └── FifthChapterTests.java
├── builders
│ ├── CategoryBuilder.java
│ ├── CreatePetRequestBuilder.java
│ └── TagsBuilder.java
├── entities
│ ├── requests
│ │ ├── Category.java
│ │ ├── CreatePetRequest.java
│ │ └── Tags.java
│ └── responses
│ │ ├── Category.java
│ │ ├── CreatePetResponse.java
│ │ └── Tags.java
└── utils
│ ├── BaseTest.java
│ ├── PropertiesReader.java
│ ├── RequestHelper.java
│ ├── ResourceHelper.java
│ └── ResponseHelper.java
└── resources
└── url.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle/
2 | .idea/
3 | gradle/
4 | out/
5 | build/
6 | *.iml
7 | *.store
--------------------------------------------------------------------------------
/ReadMe.md:
--------------------------------------------------------------------------------
1 | ## API Automation Tutorial
2 |
3 | In this tutorial you are going to learn How to Automate the REST API's in Java using RESTAssured Library
4 |
5 | The tech stack used for this tutorial are:
6 | 1. **JAVA** as the programming language for writing test code
7 | 2. **TestNg** as the framework
8 | 3. **Gradle** as the build tool
9 | 4. **IntelliJ** as the preferred IDE for writing java code.
10 |
11 | #### Getting Started
12 | Setup your machine.
13 | 1. Install JDK 1.8
14 | 2. Install IntelliJ (Community edition is fine)
15 | 3. Install Gradle
16 |
17 | #### Cloning & Importing the Project
18 | 1. Clone the project from ```git clone https://github.com/vinaykumarvvs/api-automation-tutorial.git```
19 | 2. Import the project (api-automation-tutorial) in IntelliJ ```File -> New -> Project from Existing Sources -> Browse Project Location -> build.gradle```
20 | 3. Now click on ```auto import -> Ok``` wait until the IntelliJ downloads all the dependencies
21 |
22 | #### Running tests
23 | ``Note:`` For 2nd & 3rd steps, you need to follow this way ```OpenTerminal/CMD -> cd ```
24 | 1. You can run the tests directly from the IntelliJ, by right-clicking and **Run test**.
25 | 2. For Linux/Mac users: ```gradle clean build runTests``` or ```gradle clean build test```
26 | 3. For Windows users: ```gradlew clean build runTests``` or ```gradlew clean build test```
27 |
28 | ---
29 |
30 | ## Tutorial Begins
31 |
32 | ### PetStore - Swagger
33 | Throughout this tutorial, I am going to use [PetStore-Swagger](http://petstore.swagger.io/). PetStore - Swagger is the open source project which has very good documentation with the various number of examples.
34 |
35 | #### [Chapter 1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/Chapter01.md) :: Send a GET Request and validate the Response
36 | 1. **[Test-1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/FirstChapterTests.java):** Send a get Request of an API and validate the body
37 | 2. **[Test-2](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/FirstChapterTests.java):** Send a get Request of an API by passing the Query Parameters in the URL itself
38 | 3. **[Test-3](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/FirstChapterTests.java):** Send a get Request of an API and retrieve the data from the body
39 | 4. **[Test-4](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/FirstChapterTests.java):** Send a get Request of an API and store the Response
40 |
41 | #### [Chapter 2](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter02/Chapter02.md) :: Abstracting the code
42 | 1. **[Test-1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter02/SecondChapterTests.java):** Abstracting the Requests for maintenance and readability
43 |
44 | #### [Chapter 3](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter03/Chapter03.md) :: POST Request creation and validating the Response Code
45 | 1. **[Test-1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter03/ThirdChapterTests.java):** Creating the POST Request and validating the Response Code
46 |
47 | #### [Chapter 4](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter04/Chapter04.md) :: POST Request creation and validating RequestBody & ResponseBody
48 | 1. **[Test-1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter04/FourthChapterTests.java):** Creating the POST Request and validating the RequestBody & ResponseBody
49 |
50 | #### [Chapter 5](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter05/Chapter05.md) :: Chaining the API's
51 | 1. **[Test-1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter05/FifthChapterTests.java):** Chaining Requests and validate Response Body
52 |
--------------------------------------------------------------------------------
/Tests.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'java'
3 | }
4 |
5 | group 'com.apiautomationtutorial'
6 | version '1.0-SNAPSHOT'
7 |
8 | repositories {
9 | mavenCentral()
10 | }
11 |
12 | dependencies {
13 | testImplementation group: 'org.testng', name: 'testng', version: '7.9.0'
14 | testImplementation group: 'io.rest-assured', name: 'rest-assured', version: '5.4.0'
15 | testImplementation group: 'org.hamcrest', name: 'hamcrest', version: '2.2'
16 | implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.16.1'
17 | }
18 |
19 | task runTests(type: Test) {
20 | useTestNG {
21 | useDefaultListeners = true
22 | }
23 | testLogging {
24 | events 'passed', 'skipped', 'failed'
25 | }
26 | }
27 |
28 | test {
29 | useTestNG {
30 | suites 'Tests.xml'
31 | }
32 | testLogging {
33 | events 'passed', 'skipped', 'failed'
34 | }
35 | }
36 |
37 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
88 |
89 | # Use the maximum available, or set MAX_FD != -1 to use that value.
90 | MAX_FD=maximum
91 |
92 | warn () {
93 | echo "$*"
94 | } >&2
95 |
96 | die () {
97 | echo
98 | echo "$*"
99 | echo
100 | exit 1
101 | } >&2
102 |
103 | # OS specific support (must be 'true' or 'false').
104 | cygwin=false
105 | msys=false
106 | darwin=false
107 | nonstop=false
108 | case "$( uname )" in #(
109 | CYGWIN* ) cygwin=true ;; #(
110 | Darwin* ) darwin=true ;; #(
111 | MSYS* | MINGW* ) msys=true ;; #(
112 | NONSTOP* ) nonstop=true ;;
113 | esac
114 |
115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
116 |
117 |
118 | # Determine the Java command to use to start the JVM.
119 | if [ -n "$JAVA_HOME" ] ; then
120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
121 | # IBM's JDK on AIX uses strange locations for the executables
122 | JAVACMD=$JAVA_HOME/jre/sh/java
123 | else
124 | JAVACMD=$JAVA_HOME/bin/java
125 | fi
126 | if [ ! -x "$JAVACMD" ] ; then
127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
128 |
129 | Please set the JAVA_HOME variable in your environment to match the
130 | location of your Java installation."
131 | fi
132 | else
133 | JAVACMD=java
134 | if ! command -v java >/dev/null 2>&1
135 | then
136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 | fi
142 |
143 | # Increase the maximum file descriptors if we can.
144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
145 | case $MAX_FD in #(
146 | max*)
147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
148 | # shellcheck disable=SC2039,SC3045
149 | MAX_FD=$( ulimit -H -n ) ||
150 | warn "Could not query maximum file descriptor limit"
151 | esac
152 | case $MAX_FD in #(
153 | '' | soft) :;; #(
154 | *)
155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
156 | # shellcheck disable=SC2039,SC3045
157 | ulimit -n "$MAX_FD" ||
158 | warn "Could not set maximum file descriptor limit to $MAX_FD"
159 | esac
160 | fi
161 |
162 | # Collect all arguments for the java command, stacking in reverse order:
163 | # * args from the command line
164 | # * the main class name
165 | # * -classpath
166 | # * -D...appname settings
167 | # * --module-path (only if needed)
168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
169 |
170 | # For Cygwin or MSYS, switch paths to Windows format before running java
171 | if "$cygwin" || "$msys" ; then
172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
174 |
175 | JAVACMD=$( cygpath --unix "$JAVACMD" )
176 |
177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
178 | for arg do
179 | if
180 | case $arg in #(
181 | -*) false ;; # don't mess with options #(
182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
183 | [ -e "$t" ] ;; #(
184 | *) false ;;
185 | esac
186 | then
187 | arg=$( cygpath --path --ignore --mixed "$arg" )
188 | fi
189 | # Roll the args list around exactly as many times as the number of
190 | # args, so each arg winds up back in the position where it started, but
191 | # possibly modified.
192 | #
193 | # NB: a `for` loop captures its iteration list before it begins, so
194 | # changing the positional parameters here affects neither the number of
195 | # iterations, nor the values presented in `arg`.
196 | shift # remove old arg
197 | set -- "$@" "$arg" # push replacement arg
198 | done
199 | fi
200 |
201 |
202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
204 |
205 | # Collect all arguments for the java command:
206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
207 | # and any embedded shellness will be escaped.
208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
209 | # treated as '${Hostname}' itself on the command line.
210 |
211 | set -- \
212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
213 | -classpath "$CLASSPATH" \
214 | org.gradle.wrapper.GradleWrapperMain \
215 | "$@"
216 |
217 | # Stop when "xargs" is not available.
218 | if ! command -v xargs >/dev/null 2>&1
219 | then
220 | die "xargs is not available"
221 | fi
222 |
223 | # Use "xargs" to parse quoted args.
224 | #
225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
226 | #
227 | # In Bash we could simply go:
228 | #
229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
230 | # set -- "${ARGS[@]}" "$@"
231 | #
232 | # but POSIX shell has neither arrays nor command substitution, so instead we
233 | # post-process each arg (as a line of input to sed) to backslash-escape any
234 | # character that might be a shell metacharacter, then use eval to reverse
235 | # that process (while maintaining the separation between arguments), and wrap
236 | # the whole thing up as a single "set" statement.
237 | #
238 | # This will of course break if any of these variables contains a newline or
239 | # an unmatched quote.
240 | #
241 |
242 | eval "set -- $(
243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
244 | xargs -n1 |
245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
246 | tr '\n' ' '
247 | )" '"$@"'
248 |
249 | exec "$JAVACMD" "$@"
250 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
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 %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 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 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'api-automation-tutorial'
2 |
3 |
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter01/Chapter01.md:
--------------------------------------------------------------------------------
1 | ## Chapter 1
2 |
3 | #### Pre-requisites
4 | * Basic Understanding of Java, [REST API's](https://www.sitepoint.com/developers-rest-api/) and brief idea on [JSON](https://developers.squarespace.com/what-is-json/)
5 | * Having a basic knowledge on RESTAssured Library, if not
6 | click [here](http://rest-assured.io/)
7 |
8 | #### Getting Started
9 | First, let us quickly understand the following things
10 | 1. **What is DSL?**
11 | 2. **Keywords present in RESTAssured DSL**
12 |
13 | ````What is DSL?````
14 |
15 | Domain Specific Language (DSL) DSLs are small languages, focused on a particular
16 | aspect of a software system. You can't build a whole program with a DSL,
17 | but you often use multiple DSLs in a system mainly written in a general purpose language.
18 |
19 | ````Keywords present in RESTAssured DSL````
20 | 1. given()
21 | 2. when()
22 | 3. body()
23 | 4. extract()
24 |
25 | And other Keywords are used following to the `given|when|then|extract`. Click [here](https://github.com/rest-assured/rest-assured/wiki/usage)
26 | to check a few more keywords.
27 | #### Sequence of creating a Request and receiving a Response
28 | 1. `given()` - These are the configs that we can define following to the current keyword
29 | * QueryParameters
30 | * Body
31 | * Headers
32 | 2. `when()` - These are the following actions that can be implemented after this keyword
33 | * HTTP Method ( get, POST, PUT, DELETE....)
34 | 3. `then()` - Validations/Assertions need to be implemented after this keyword
35 | 4. `extract()` - To retrieve a single value from JSON
36 |
37 | 
38 |
39 | **Note:** Before getting into tests, we need to add the dependencies in Gradle File. Click here to check the
40 | [Gradle Config](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/Chapter01GradleConfig.md)
41 |
42 | This Chapter consists of four tests
43 | 1. **Test-1:** Send a get Request of an API and validate the body
44 | 2. **Test-2:** Send a get Request of an API by passing the Query Parameters in the URL itself
45 | 3. **Test-3:** Send a get Request of an API and retrieve the data from the body
46 | 4. **Test-4:** Send a get Request of an API and store the Response
47 |
48 | #### **Test-1:** Send a GET Request of an API and validate the body
49 | In this test we are going to Send a Request and Validate the JSON body
50 | 1. `queryParam()` - Filter the Data with a given values
51 | 2. `get()` - HTTP Method
52 | 3. `statusCode()` - Response StatusCode
53 | 4. `body()` - To get the data from the JSON and verify it.
54 |
55 | #### **Test-2:** Send a get Request of an API by passing the Query Parameters in the URL itself
56 | In the above test, we have seen how to pass the query parameters separately. Now let's see how to pass it in another way
57 | 1. Not only in the `queryParameter()` section we can even pass the parameters in the URL itself.
58 | This approach is good when we have a common `GET` method across all API's.
59 |
60 | #### **Test-3:** Send a GET Request of an API and retrieve the data from a body
61 | In this test, we are going to Send a Request and retrieve some data from the Response
62 | 1. `extract()` - It is used to return any value from the JSON
63 |
64 | #### **Test-4:** Send a GET Request of an API and store the Response
65 | Previously we have seen how to retrieve a single value. Now in this test, we are going to store entire Response
66 | 1. `Response response = given()...` - This way we can store the Response
67 |
68 | 
69 |
70 | 2. `response.getStatusCode` - Will return the StatusCode
71 | 3. `response.getBody().asString()` - Returns entire JSON Body in a String format
72 |
73 | #### Summary
74 | In this Chapter, we have learned about
75 | 1. How to create and send a Request for a get API
76 | 2. How to retrieve single data from JSON body
77 | 3. How to Store the Response
78 |
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter01/Chapter01GradleConfig.md:
--------------------------------------------------------------------------------
1 | ## Gradle Configuration
2 |
3 | ``Gradle is a build tool used to manage all the dependencies``
4 |
5 | #### Add the following Dependencies in `build.gradle`
6 | 1. `testCompile group: 'org.testng', name: 'testng', version: '6.14.3'` - For TestNG
7 | 2. `testCompile 'io.rest-assured:rest-assured:3.0.6'` - This is to get all RESTAssured libraries
8 | 3. `testCompile group: 'org.hamcrest', name: 'java-hamcrest', version: '2.0.0.0'` - To get predefined assertions
9 |
10 | After adding the dependencies your block should look like
11 |
12 | 
13 |
14 | #### Create a task for running tests from the command line
15 | * Add the following lines of code in your `build.gradle` file
16 | * This will make you execute all the tests present in the project from command line with `@Test` Annotation.
17 |
18 | 
19 |
20 | #### Now, the Gradle file should be:
21 |
22 | 
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter01/FirstChapterTests.java:
--------------------------------------------------------------------------------
1 | package Chapters.Chapter01;
2 |
3 | import io.restassured.response.Response;
4 | import org.testng.Assert;
5 | import org.testng.annotations.Test;
6 |
7 | import static io.restassured.RestAssured.given;
8 | import static org.hamcrest.Matchers.equalTo;
9 | import static org.hamcrest.Matchers.notNullValue;
10 |
11 | public class FirstChapterTests {
12 |
13 | private static final String BASE_URL = "https://petstore.swagger.io/v2";
14 |
15 | // In this test, we are going to test a GET API and validate the Response
16 | @Test
17 | public void sendAGETRequestAndValidateResponse() {
18 | given()
19 | .queryParam("status", "sold") // Filtering the data based on
20 | .when()
21 | .get(BASE_URL + "/pet/findByStatus") // This will get the data from the given URL
22 | .then()
23 | .statusCode(200) // It verify the actual response code with the given code
24 | .body("[0].id", notNullValue()) // Checking whether value is Not_Null or not
25 | .body("[0].name", notNullValue())
26 | .body("[0].status", equalTo("sold")); // Checking status is equal to "sold"
27 | }
28 |
29 | // Here we testing the GET API, by passing the query parameters in the URL
30 | @Test
31 | public void sendAGETRequestByPassingQueryParameterInURL() {
32 | given()
33 | .when()
34 | .get(BASE_URL + "/pet/findByStatus?status=sold") // Passing query parameters in URL itself
35 | .then()
36 | .statusCode(200)
37 | .body("[0].id", notNullValue())
38 | .body("[0].name", notNullValue())
39 | .body("[0].status", equalTo("sold"));
40 | }
41 |
42 | // In this test we are going to extract single value from the response
43 | @Test
44 | public void sendAGETRequestAndRetrieveValueFromBody() {
45 | String status = given()
46 | .queryParam("status", "sold")
47 | .when()
48 | .get(BASE_URL + "/pet/findByStatus")
49 | .then()
50 | .extract()
51 | .path("[0].status"); // Extracting the value from JSON and returning it
52 |
53 | if (status == null)
54 | throw new RuntimeException("Status is Empty!!!");
55 | }
56 |
57 | // This test will store the entire Response into Response Object
58 | @Test
59 | public void sendAGETRequestAndStoreTheResponse() {
60 | Response response = given()
61 | .queryParam("status", "sold")
62 | .when()
63 | .get(BASE_URL + "/pet/findByStatus"); // Finally it returns the Response
64 |
65 | Assert.assertEquals(response.getStatusCode(), 200);
66 | }
67 | }
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter02/Chapter02.md:
--------------------------------------------------------------------------------
1 | ## Chapter 2
2 |
3 | #### Pre-requisites
4 | * To get started with the Second Chapter, I recommend you to go through the [Chapter 1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/Chapter01.md).
5 | * If you are reading this line then you are good to go. Let's get started with the Second Chapter
6 |
7 | #### **Before getting into the Tests**
8 | These are the things we have done in the First Chapter that are not recommended. In a layman approach, we can simply say that First Chapter is very tightly coupled.
9 | 1. Hard-coded the `BASE_URL`
10 | 2. And if you observe, in every test we are repeating the same lines of code like `given|when|then|get..` for the same functionality.
11 |
12 | #### **Agenda for this Chapter**
13 | Now in this chapter, we are going to optimize the code what we have used for First Chapter, by doing this anyone can easily
14 | read and maintain the code.
15 |
16 | #### **Optimizing**
17 | In order to optimize the code, we have introduced the following Java Files.
18 | 1. [PropertiesReader](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/utils/PropertiesReader.java) - It is used to read the URL's from the Properties file.
19 | 2. [ResourceHelper](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/utils/ResourceHelper.java) - This Java file is used to implement all HTTP Methods
20 | 3. [BaseTest](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/utils/BaseTest.java) - Every test needs to extend this Java File. In this file, we can have `Hooks|CommonsMethods`
21 |
22 | ```After introducing the above files we can clearly say that our project is loosely coupled and easily maintainable```.
23 |
24 | #### **Tests**
25 | This Chapter consists only one test
26 | 1. **Test-1:** Abstracting the Requests for maintenance and readability
27 |
28 | #### Summary
29 | Things we have learned so far from [Chapter 1](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter01/Chapter01.md)
30 | and [Chapter 2](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter02/Chapter02.md)
31 | 1. How to send the Request and receive the Response.
32 | 2. How to segregate the code based on their functionality by following `Single Responsibility Principle`.
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter02/SecondChapterTests.java:
--------------------------------------------------------------------------------
1 | package Chapters.Chapter02;
2 |
3 | import io.restassured.response.Response;
4 | import org.testng.Assert;
5 | import org.testng.annotations.Test;
6 | import utils.BaseTest;
7 | import utils.ResourceHelper;
8 |
9 | public class SecondChapterTests extends BaseTest {
10 |
11 | // Abstracting the code for more readability and maintainability
12 | @Test
13 | public void abstractingTheRequestForMaintenanceAndReadability() {
14 | Response response = ResourceHelper.get(propertiesReader.getEndPointUrl("get_animals"));
15 | Assert.assertEquals(response.getStatusCode(), 200);
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter03/Chapter03.md:
--------------------------------------------------------------------------------
1 | ## Chapter 3
2 |
3 | #### **Pre-requisites**
4 | * To get started with the Third Chapter, I recommend you to go through the [Chapter 2](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter02/Chapter02.md).
5 | * If you are reading this line then you are good to go. Let's get started with the Third Chapter
6 |
7 | #### **Quick Recap**
8 | Here are some listings, we have learned till now
9 | 1. How to send a GET Request
10 | 2. How to validate the Response
11 | 3. And also we have seen, How to segregate the things in order to maintain `Single Responsibility Principle`.
12 |
13 | #### **Agenda for this Chapter**
14 | In this chapter, we are going to create the POST Request using Entity-Builder pattern and validate the
15 | Response StatusCode. Here is the quick reference for [Why & What is Entity-Builder-Pattern](https://dzone.com/articles/the-builder-pattern-for-test-classes)
16 |
17 | #### **Request JSON**
18 | Here is the JSON that we are going to use for Creating a Pet.
19 | This JSON reference I have taken it from [PetStore-Swagger](http://petstore.swagger.io/).
20 |
21 | 
22 |
23 | #### **Create Entities and Builders**
24 | In the above JSON, we have seen some couple of Objects. So lets create the
25 | Java files for the above mentioned JSON. Here is the references to the JAVA files
26 | 1. [Category](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/entities/requests/Category.java) & [CategoryBuilder](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/builders/CategoryBuilder.java)
27 | 2. [Tags](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/entities/requests/Tags.java) & [TagsBuilder](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/builders/TagsBuilder.java)
28 | 3. [CreatePetRequest](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/entities/requests/CreatePetRequest.java) & [CreatePetRequestBuilder](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/builders/CreatePetRequestBuilder.java)
29 |
30 | #### **Gradle Config**
31 | Before getting into the tests we need to add the following dependency in `build.gradle`
32 | 1. `compile group: 'org.codehaus.jackson', name: 'jackson-mapper-asl', version: '1.8.5'` - This library is used to convert the Java
33 | object into a String. Your final dependency block should look like
34 |
35 | 
36 |
37 | #### **Introducing RequestHelper**
38 | * [RequestHelper](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/utils/RequestHelper.java) - helps us to convert the Java object into a String.
39 | It takes input as an object and returns the String.
40 |
41 | #### **Tests**
42 | This Chapter consists only one test
43 | 1. **Test-1:** Creating the POST Request and validating the Response Code
44 |
45 | In this test, we are doing the following actions:
46 |
47 | a. Create an object for Category with some data
48 | b. Create an object for Tags with some data and inserting in the TagsList
49 | c. Now create a main object CreatePetRequest
50 | d. Then serialize the object into JSON String and sending it in the body
51 | e. Validate the Response Status-Code
52 |
53 | #### **Summary**
54 | Things we have learned so far:
55 | 1. How to send the GET Request and receive the Response.
56 | 2. How to segregate the code based on their functionality by following `Single Responsibility Principle`.
57 | 3. How to create and send the POST Request using `Entity-Builder` pattern.
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter03/ThirdChapterTests.java:
--------------------------------------------------------------------------------
1 | package Chapters.Chapter03;
2 |
3 | import builders.CategoryBuilder;
4 | import builders.CreatePetRequestBuilder;
5 | import builders.TagsBuilder;
6 | import entities.requests.Category;
7 | import entities.requests.CreatePetRequest;
8 | import entities.requests.Tags;
9 | import io.restassured.response.Response;
10 | import org.testng.Assert;
11 | import org.testng.annotations.Test;
12 | import utils.BaseTest;
13 | import utils.RequestHelper;
14 | import utils.ResourceHelper;
15 |
16 | public class ThirdChapterTests extends BaseTest {
17 |
18 | @Test
19 | public void sendAPOSTRequestAndValidateTheResponseCode() {
20 |
21 | // Creating the Category Object
22 | Category category = new CategoryBuilder()
23 | .withId(1)
24 | .withName("Cats")
25 | .build();
26 |
27 | // Creating the Tags Object
28 | Tags tags = new TagsBuilder()
29 | .withId(1)
30 | .withName("Tag 1")
31 | .build();
32 |
33 | // Inserting the above created Tags object in the TagsList, because main object accepts as an array
34 | Tags[] tagsList = new Tags[1];
35 | tagsList[0] = tags;
36 |
37 | // Creating the Main Object - CreatePetRequest
38 | String[] photoUrls = {"Photo Url"}; // Create an array with some URL's
39 | CreatePetRequest createPetRequest = new CreatePetRequestBuilder()
40 | .withCategory(category)
41 | .withTags(tagsList)
42 | .withPhotoUrls(photoUrls)
43 | .withId(get3DigitRandomInt()) // This `get3DigitRandomInt()` will generate the random 3 digit number, coming from BaseTest
44 | .withName("Testing + " + get3DigitRandomInt())
45 | .withStatus("available")
46 | .build();
47 |
48 | // Sending a Request
49 | String url = propertiesReader.getEndPointUrl("create_pet"); // Fetching url from Properties file
50 | String json = RequestHelper.getJsonString(createPetRequest); // Convert above created object into a String
51 | Response response = ResourceHelper.create(url, json);
52 |
53 | // Validating the Response Code
54 | Assert.assertEquals(response.getStatusCode(), 200);
55 |
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter04/Chapter04.md:
--------------------------------------------------------------------------------
1 | ## Chapter 4
2 |
3 | #### **Pre-requisites**
4 | * To get started with the Fourth Chapter, I recommend you to go through the [Chapter 3](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter03/Chapter03.md).
5 | * If you are reading this line then you are good to go. Let's get started with the Fourth Chapter
6 |
7 | #### **Quick Recap**
8 | Here are some listing, we have learned till now
9 | 1. How to send a GET Request
10 | 2. How to validate the Response
11 | 3. How to segregate the things in order to maintain `Single Responsibility Principle`.
12 | 4. And also, How to send the POST Request using Entity-Builder pattern and validate the Response Code.
13 |
14 | #### **Agenda for this Chapter**
15 | Till now we know how to send a POST Request and validate only the Response Code, Do you think is this sufficient?.
16 | Don't worry in this chapter we are going to validate the Response body as well. So let's get started.
17 |
18 | #### **Response JSON**
19 | Here is the Response JSON, this JSON will be output when we POST the Request to server.
20 |
21 | 
22 |
23 | #### **Create Entities**
24 | 1. As we have seen the Response JSON in the above picture, we can clearly observe that in Response JSON also
25 | we have three Objects `Category, Tags & Main Object`. These objects are very similar to the one which we have created
26 | for the POST method.
27 | 2. We can use the same one, but this approach is not recommended. Because if someday Request changes and Response is not changed
28 | then at that time it will be difficult to map the Java Object to JSON String or vice-versa.
29 | 3. So, now we are going to create only entities for [Category](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/entities/responses/Category.java),
30 | [Tags](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/entities/responses/Tags.java) &
31 | [CreatePetResponse](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/entities/responses/CreatePetResponse.java).
32 | ( Here we can have any name for the Main Object, but for the inner objects we need use the same name )
33 |
34 | #### **Introducing Response Helper**
35 | So, in the previous chapter we have seen How to convert the Java Object to a JSON String using RequestHelper, now
36 | we are introducing [ResponseHelper](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/utils/ResponseHelper.java)
37 | to convert the String into a Java object.
38 |
39 | #### **Tests**
40 | This Chapter consists only one test
41 | 1. **Test-1:** Creating the POST Request and validating the RequestBody & ResponseBody
42 |
43 | In this test, we are doing the following actions:
44 |
45 | a. Create an object for Category with some data
46 | b. Create an object for Tags with some data and inserting in the TagsList
47 | c. Now create a main object CreatePetRequest
48 | d. Then serialize the object into JSON String and sending it in the body
49 | e. Once we receive the Response, with the help of ResponseHelper we can de-serialize JSON String to Java Object
50 | f. Verify the attributes from RequestBody & ResponseBody
51 |
52 | #### **Summary**
53 | Things we have learned so far:
54 | 1. How to send the GET Request and receive the Response.
55 | 2. How to segregate the code based on their functionality by following `Single Responsibility Principle`.
56 | 3. How to create and send the POST Request using `Entity-Builder` pattern.
57 | 4. How to verify the RequestBody & ResponseBody
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter04/FourthChapterTests.java:
--------------------------------------------------------------------------------
1 | package Chapters.Chapter04;
2 |
3 | import builders.CategoryBuilder;
4 | import builders.CreatePetRequestBuilder;
5 | import builders.TagsBuilder;
6 | import entities.requests.Category;
7 | import entities.requests.CreatePetRequest;
8 | import entities.requests.Tags;
9 | import entities.responses.CreatePetResponse;
10 | import io.restassured.response.Response;
11 | import org.testng.Assert;
12 | import org.testng.annotations.Test;
13 | import utils.BaseTest;
14 | import utils.RequestHelper;
15 | import utils.ResourceHelper;
16 | import utils.ResponseHelper;
17 |
18 | import java.io.IOException;
19 |
20 | public class FourthChapterTests extends BaseTest {
21 |
22 | @Test
23 | public void sendPOSTRequestAndValidateResponseBody() throws IOException {
24 | // Creating the Category Object
25 | Category category = new CategoryBuilder()
26 | .withId(1)
27 | .withName("Cats")
28 | .build();
29 |
30 | // Creating the Tags Object
31 | Tags tags = new TagsBuilder()
32 | .withId(1)
33 | .withName("Tag 1")
34 | .build();
35 |
36 | // Inserting the above created Tags object in the TagsList, because main object accepts as an array
37 | Tags[] tagsList = new Tags[1];
38 | tagsList[0] = tags;
39 |
40 | // Creating the Main Object - CreatePetRequest
41 | String[] photoUrls = {"Photo Url"}; // Create an array with some URL's
42 | CreatePetRequest createPetRequest = new CreatePetRequestBuilder()
43 | .withCategory(category)
44 | .withTags(tagsList)
45 | .withPhotoUrls(photoUrls)
46 | .withId(get3DigitRandomInt()) // This `get3DigitRandomInt()` will generate the random 3 digit number, coming from BaseTest
47 | .withName("Testing + " + get3DigitRandomInt())
48 | .withStatus("available")
49 | .build();
50 |
51 | // Sending a Request
52 | String url = propertiesReader.getEndPointUrl("create_pet"); // Fetching url from Properties file
53 | String json = RequestHelper.getJsonString(createPetRequest); // Convert above created object into a String
54 | Response response = ResourceHelper.create(url, json);
55 |
56 | // Binding Response body to the Java Object
57 | CreatePetResponse createPetResponse = (CreatePetResponse)
58 | ResponseHelper.getResponseAsObject(response.asString(), CreatePetResponse.class);
59 |
60 | // Validating the Response Code
61 | Assert.assertEquals(response.getStatusCode(), 200);
62 |
63 | // Validating the RequestBody & ResponseBody
64 | Assert.assertEquals(createPetRequest.getName(), createPetResponse.getName());
65 | Assert.assertEquals(createPetRequest.getStatus(), createPetResponse.getStatus());
66 | Assert.assertEquals(createPetRequest.getTags()[0].getName(), createPetResponse.getTags()[0].getName());
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter05/Chapter05.md:
--------------------------------------------------------------------------------
1 | ## Chapter 5
2 |
3 | #### **Pre-requisites**
4 | * To get started with the Fourth Chapter, I recommend you to go through the [Chapter 4](https://github.com/vinaykumarvvs/api-automation-tutorial/tree/master/src/test/java/Chapters/Chapter04/Chapter04.md).
5 | * If you are reading this line then you are good to go. Let's get started with the Fifth Chapter
6 |
7 | #### **Quick Recap**
8 | Here are some listing, we have learned till now
9 | 1. How to send a GET Request
10 | 2. How to validate the Response
11 | 3. How to segregate the things in order to maintain `Single Responsibility Principle`.
12 | 4. How to send the POST Request using Entity-Builder pattern and validate the Response Code.
13 | 5. And also, How to validate RequestBody & ResponseBody
14 |
15 | #### **Agenda for this Chapter**
16 | * Till now we have seen how to send a Request and receive the Response, and their validations. Now we are going to see
17 | How to Chain the API's. What is Chaining? It is a process where we can pass the information from one HTTP Request to other HTTP Requests.
18 |
19 | #### **Tests**
20 | This Chapter consists only one test
21 | 1. **Test-1:** Chaining Requests and validate Response Body
22 |
23 | In this test, we are doing the following actions:
24 | POST Request
25 | a. Create an object for Category with some data
26 | b. Create an object for Tags with some data and inserting in the TagsList
27 | c. Now create a main object CreatePetRequest
28 | d. Then serialize the object into JSON String and sending it in the body
29 | e. Once we receive the Response, with the help of ResponseHelper we can de-serialize JSON String to Java Object
30 | f. Verify the attributes from RequestBody & ResponseBody
31 |
32 | GET Request
33 | g. Creating a GET Request using the PetId and verifying the other data
34 |
35 | ```Similarly, we can chain the HTTP Requests with other methods as well. Like POST -> GET -> PUT -> DELETE ..```
36 |
37 | #### **Summary**
38 | Things we have learned so far:
39 | 1. How to send the GET Request and receive the Response.
40 | 2. How to segregate the code based on their functionality by following `Single Responsibility Principle`.
41 | 3. How to create and send the POST Request using `Entity-Builder` pattern.
42 | 4. How to verify the RequestBody & ResponseBody
43 | 5. How to chain the API's
--------------------------------------------------------------------------------
/src/test/java/Chapters/Chapter05/FifthChapterTests.java:
--------------------------------------------------------------------------------
1 | package Chapters.Chapter05;
2 |
3 | import builders.CategoryBuilder;
4 | import builders.CreatePetRequestBuilder;
5 | import builders.TagsBuilder;
6 | import entities.requests.Category;
7 | import entities.requests.CreatePetRequest;
8 | import entities.requests.Tags;
9 | import entities.responses.CreatePetResponse;
10 | import io.restassured.response.Response;
11 | import org.testng.Assert;
12 | import org.testng.annotations.Test;
13 | import utils.BaseTest;
14 | import utils.RequestHelper;
15 | import utils.ResourceHelper;
16 | import utils.ResponseHelper;
17 |
18 | import java.io.IOException;
19 |
20 | public class FifthChapterTests extends BaseTest {
21 |
22 | @Test
23 | public void chainingRequestsAndValidatingTheResponse() throws IOException {
24 |
25 | // Creating the Category Object
26 | Category category = new CategoryBuilder()
27 | .withId(1)
28 | .withName("Cats")
29 | .build();
30 |
31 | // Creating the Tags Object
32 | Tags tags = new TagsBuilder()
33 | .withId(1)
34 | .withName("Tag 1")
35 | .build();
36 |
37 | // Inserting the above created Tags object in the TagsList, because main object accepts as an array
38 | Tags[] tagsList = new Tags[1];
39 | tagsList[0] = tags;
40 |
41 | // Creating the Main Object - CreatePetRequest
42 | String[] photoUrls = {"Photo Url"}; // Create an array with some URL's
43 | CreatePetRequest createPetRequest = new CreatePetRequestBuilder()
44 | .withCategory(category)
45 | .withTags(tagsList)
46 | .withPhotoUrls(photoUrls)
47 | .withId(get3DigitRandomInt()) // This `get3DigitRandomInt()` will generate the random 3 digit number, coming from BaseTest
48 | .withName("Testing + " + get3DigitRandomInt())
49 | .withStatus("available")
50 | .build();
51 |
52 | // Sending a Request
53 | String url = propertiesReader.getEndPointUrl("create_pet"); // Fetching url from Properties file
54 | String json = RequestHelper.getJsonString(createPetRequest); // Convert above created object into a String
55 | Response response = ResourceHelper.create(url, json);
56 |
57 | // Binding Response body to the Java Object
58 | CreatePetResponse createPetResponse = (CreatePetResponse)
59 | ResponseHelper.getResponseAsObject(response.asString(), CreatePetResponse.class);
60 |
61 | // Validating the Response Code
62 | Assert.assertEquals(response.getStatusCode(), 200);
63 |
64 | // Validating the RequestBody & ResponseBody
65 | Assert.assertEquals(createPetRequest.getName(), createPetResponse.getName());
66 | Assert.assertEquals(createPetRequest.getStatus(), createPetResponse.getStatus());
67 | Assert.assertEquals(createPetRequest.getTags()[0].getName(), createPetResponse.getTags()[0].getName());
68 |
69 | // Verifying the Created Pet using GET Method
70 | String url1 = propertiesReader.getEndPointUrl("get_animal_based_on_pet_id") + createPetRequest.getId();// Concatenating the EndPoint & PetId
71 | Response findSpecificPetResponse = ResourceHelper.get(url1);
72 |
73 | // Binding Response body to the Java Object
74 | CreatePetResponse getPetResponseBasedOnId = (CreatePetResponse)
75 | ResponseHelper.getResponseAsObject(findSpecificPetResponse.asString(), CreatePetResponse.class);
76 |
77 | Assert.assertEquals(findSpecificPetResponse.getStatusCode(), 200);
78 | Assert.assertEquals(createPetRequest.getId(), getPetResponseBasedOnId.getId());
79 | Assert.assertEquals(createPetRequest.getName(), getPetResponseBasedOnId.getName());
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/test/java/builders/CategoryBuilder.java:
--------------------------------------------------------------------------------
1 | package builders;
2 |
3 | import entities.requests.Category;
4 |
5 | public class CategoryBuilder {
6 |
7 | private Category category = new Category();
8 |
9 | public CategoryBuilder withId(int id) {
10 | category.setId(id);
11 | return this;
12 | }
13 |
14 | public CategoryBuilder withName(String name) {
15 | category.setName(name);
16 | return this;
17 | }
18 |
19 | public Category build() {
20 | return category;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/builders/CreatePetRequestBuilder.java:
--------------------------------------------------------------------------------
1 | package builders;
2 |
3 | import entities.requests.Category;
4 | import entities.requests.CreatePetRequest;
5 | import entities.requests.Tags;
6 |
7 | public class CreatePetRequestBuilder {
8 |
9 | private CreatePetRequest createPetRequest = new CreatePetRequest();
10 |
11 | public CreatePetRequestBuilder withTags(Tags[] tags){
12 | createPetRequest.setTags(tags);
13 | return this;
14 | }
15 |
16 | public CreatePetRequestBuilder withCategory(Category category){
17 | createPetRequest.setCategory(category);
18 | return this;
19 | }
20 |
21 | public CreatePetRequestBuilder withId(int id){
22 | createPetRequest.setId(id);
23 | return this;
24 | }
25 |
26 | public CreatePetRequestBuilder withStatus(String status){
27 | createPetRequest.setStatus(status);
28 | return this;
29 | }
30 |
31 | public CreatePetRequestBuilder withName(String name){
32 | createPetRequest.setName(name);
33 | return this;
34 | }
35 |
36 | public CreatePetRequestBuilder withPhotoUrls(String[] photoUrls){
37 | createPetRequest.setPhotoUrls(photoUrls);
38 | return this;
39 | }
40 |
41 | public CreatePetRequest build(){
42 | return createPetRequest;
43 | }
44 |
45 | }
46 |
--------------------------------------------------------------------------------
/src/test/java/builders/TagsBuilder.java:
--------------------------------------------------------------------------------
1 | package builders;
2 |
3 | import entities.requests.Tags;
4 |
5 | public class TagsBuilder {
6 |
7 | private Tags tags = new Tags();
8 |
9 | public TagsBuilder withId(int id) {
10 | tags.setId(id);
11 | return this;
12 | }
13 |
14 | public TagsBuilder withName(String name) {
15 | tags.setName(name);
16 | return this;
17 | }
18 |
19 | public Tags build(){
20 | return tags;
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/test/java/entities/requests/Category.java:
--------------------------------------------------------------------------------
1 | package entities.requests;
2 |
3 | public class Category {
4 |
5 | private int id;
6 | private String name;
7 |
8 | public int getId() {
9 | return id;
10 | }
11 |
12 | public void setId(int id) {
13 | this.id = id;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | public void setName(String name) {
21 | this.name = name;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/entities/requests/CreatePetRequest.java:
--------------------------------------------------------------------------------
1 | package entities.requests;
2 |
3 | public class CreatePetRequest {
4 |
5 | private Tags[] tags;
6 | private int id;
7 | private Category category;
8 | private String status;
9 | private String name;
10 | private String[] photoUrls;
11 |
12 | public Tags[] getTags() {
13 | return tags;
14 | }
15 |
16 | public void setTags(Tags[] tags) {
17 | this.tags = tags;
18 | }
19 |
20 | public int getId() {
21 | return id;
22 | }
23 |
24 | public void setId(int id) {
25 | this.id = id;
26 | }
27 |
28 | public Category getCategory() {
29 | return category;
30 | }
31 |
32 | public void setCategory(Category category) {
33 | this.category = category;
34 | }
35 |
36 | public String getStatus() {
37 | return status;
38 | }
39 |
40 | public void setStatus(String status) {
41 | this.status = status;
42 | }
43 |
44 | public String getName() {
45 | return name;
46 | }
47 |
48 | public void setName(String name) {
49 | this.name = name;
50 | }
51 |
52 | public String[] getPhotoUrls() {
53 | return photoUrls;
54 | }
55 |
56 | public void setPhotoUrls(String[] photoUrls) {
57 | this.photoUrls = photoUrls;
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/test/java/entities/requests/Tags.java:
--------------------------------------------------------------------------------
1 | package entities.requests;
2 |
3 | public class Tags {
4 |
5 | private int id;
6 | private String name;
7 |
8 | public int getId() {
9 | return id;
10 | }
11 |
12 | public void setId(int id) {
13 | this.id = id;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | public void setName(String name) {
21 | this.name = name;
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/src/test/java/entities/responses/Category.java:
--------------------------------------------------------------------------------
1 | package entities.responses;
2 |
3 | public class Category {
4 |
5 | private int id;
6 | private String name;
7 |
8 | public int getId() {
9 | return id;
10 | }
11 |
12 | public void setId(int id) {
13 | this.id = id;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | public void setName(String name) {
21 | this.name = name;
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/test/java/entities/responses/CreatePetResponse.java:
--------------------------------------------------------------------------------
1 | package entities.responses;
2 |
3 | import entities.requests.Category;
4 | import entities.requests.Tags;
5 |
6 | public class CreatePetResponse {
7 |
8 | private Tags[] tags;
9 | private int id;
10 | private Category category;
11 | private String status;
12 | private String name;
13 | private String[] photoUrls;
14 |
15 | public Tags[] getTags() {
16 | return tags;
17 | }
18 |
19 | public void setTags(Tags[] tags) {
20 | this.tags = tags;
21 | }
22 |
23 | public int getId() {
24 | return id;
25 | }
26 |
27 | public void setId(int id) {
28 | this.id = id;
29 | }
30 |
31 | public Category getCategory() {
32 | return category;
33 | }
34 |
35 | public void setCategory(Category category) {
36 | this.category = category;
37 | }
38 |
39 | public String getStatus() {
40 | return status;
41 | }
42 |
43 | public void setStatus(String status) {
44 | this.status = status;
45 | }
46 |
47 | public String getName() {
48 | return name;
49 | }
50 |
51 | public void setName(String name) {
52 | this.name = name;
53 | }
54 |
55 | public String[] getPhotoUrls() {
56 | return photoUrls;
57 | }
58 |
59 | public void setPhotoUrls(String[] photoUrls) {
60 | this.photoUrls = photoUrls;
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/test/java/entities/responses/Tags.java:
--------------------------------------------------------------------------------
1 | package entities.responses;
2 |
3 | public class Tags {
4 |
5 | private int id;
6 | private String name;
7 |
8 | public int getId() {
9 | return id;
10 | }
11 |
12 | public void setId(int id) {
13 | this.id = id;
14 | }
15 |
16 | public String getName() {
17 | return name;
18 | }
19 |
20 | public void setName(String name) {
21 | this.name = name;
22 | }
23 |
24 | }
--------------------------------------------------------------------------------
/src/test/java/utils/BaseTest.java:
--------------------------------------------------------------------------------
1 | package utils;
2 |
3 | import org.apache.commons.lang3.RandomUtils;
4 | import org.testng.annotations.AfterTest;
5 | import org.testng.annotations.BeforeTest;
6 |
7 | public class BaseTest {
8 |
9 | protected static PropertiesReader propertiesReader = new PropertiesReader();
10 |
11 | @BeforeTest
12 | public void setUp() {
13 | System.out.println("This test is started");
14 | }
15 |
16 | @AfterTest
17 | public void tearDown() {
18 | System.out.println("This test is completed");
19 | }
20 |
21 | protected int get3DigitRandomInt() {
22 | return RandomUtils.nextInt(100, 999);
23 | }
24 |
25 | }
26 |
27 |
--------------------------------------------------------------------------------
/src/test/java/utils/PropertiesReader.java:
--------------------------------------------------------------------------------
1 | package utils;
2 |
3 | import java.io.FileInputStream;
4 | import java.io.IOException;
5 | import java.io.InputStream;
6 | import java.util.Properties;
7 |
8 | public class PropertiesReader {
9 |
10 | private Properties prop = new Properties();
11 | private InputStream inputStream = null;
12 |
13 | public PropertiesReader() {
14 | try {
15 | String propertiesFilePath = System.getProperty("user.dir") + "/src/test/resources/url.properties";
16 | inputStream = new FileInputStream(propertiesFilePath);
17 | prop.load(inputStream);
18 | } catch (IOException e) {
19 | e.printStackTrace();
20 | }
21 | }
22 |
23 | public String getEndPointUrl(String endpoint) {
24 | return prop.getProperty("base_url") + prop.getProperty(endpoint);
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/test/java/utils/RequestHelper.java:
--------------------------------------------------------------------------------
1 | package utils;
2 |
3 | import com.fasterxml.jackson.annotation.JsonInclude;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 |
6 | import java.io.IOException;
7 |
8 | public class RequestHelper {
9 |
10 | public static String getJsonString(Object o) {
11 | ObjectMapper objectMapper = new ObjectMapper();
12 | objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
13 |
14 | try {
15 | return objectMapper.writeValueAsString(o);
16 | } catch (IOException e) {
17 | e.printStackTrace();
18 | }
19 | return "";
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/test/java/utils/ResourceHelper.java:
--------------------------------------------------------------------------------
1 | package utils;
2 |
3 | import io.restassured.response.Response;
4 |
5 | import static io.restassured.RestAssured.given;
6 |
7 | public class ResourceHelper {
8 |
9 | public static Response get(String url) {
10 | return given().when().get(url);
11 | }
12 |
13 | public static Response create(String url, String json) {
14 | return given()
15 | .header("Content-Type", "application/json")
16 | .when()
17 | .body(json)
18 | .post(url);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/test/java/utils/ResponseHelper.java:
--------------------------------------------------------------------------------
1 | package utils;
2 |
3 | import com.fasterxml.jackson.databind.DeserializationFeature;
4 | import com.fasterxml.jackson.databind.ObjectMapper;
5 |
6 | import java.io.IOException;
7 |
8 | public class ResponseHelper {
9 |
10 | public static Object getResponseAsObject(String responseString, Class responseClass) throws IOException {
11 | ObjectMapper mapper = new ObjectMapper();
12 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
13 | return mapper.readValue(responseString, responseClass);
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/test/resources/url.properties:
--------------------------------------------------------------------------------
1 | base_url=https://petstore.swagger.io/v2
2 | get_animals=/pet/findByStatus?status=available
3 | create_pet=/pet
4 | get_animal_based_on_pet_id=/pet/
--------------------------------------------------------------------------------