0% found this document useful (0 votes)
15 views28 pages

REST Assured Automation Resource 1

The document discusses automation testing using the TestNG framework. It covers TestNG annotations and features like parallel execution, soft assertions, grouping tests, and designing test suites and testng.xml files.

Uploaded by

sahana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views28 pages

REST Assured Automation Resource 1

The document discusses automation testing using the TestNG framework. It covers TestNG annotations and features like parallel execution, soft assertions, grouping tests, and designing test suites and testng.xml files.

Uploaded by

sahana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Mastering REST API Automation using REST Assured

By Sidharth Shukla and The Test Tribe

REST Assured Automation Resource


2

Index

1. Parallel with group


2. Collection Runner in Postman
3. How to upload & download files using Rest Assured?
4. What are serialization & deserialization in Java and REST Assured?
5. TestNG
6. How to create suites using TestNG?
7. How to create test suites using Class?
8. How to create test suites using Package?
9. Parallel TestNG Execution for Classes
10. Parallel TestNG Execution for Tests
11. Soft Assertions in TestNG
12. Soft Assert vs Hard Assert
13. Parameters & dataprovider with TestNG
14. RetryListener
15. Extent Report
16. How to install Jenkins server in Windows, Mac and Linux machines with
official links
17. How to use spec builder?
18. READ JSON ARRAY
19. Fetch data from an array
3

Parallel with group

Collection Runner in Postman

Postman's Collection Runner is a tool that allows you to execute a collection


of API requests and get their responses in a single run. It helps you to test and
automate the API requests that you have saved in a collection in Postman.

Here are the steps to use Collection Runner in Postman:

1. Open the Postman app and select the collection you want to run in the
left sidebar.
2. Click on the "Runner" button on the top-right corner of the app.
3. In the Collection Runner window, you can configure the following
options:
● Environment: Select the environment you want to use for running the
collection. An environment is a set of variables that you can use in your
requests to parameterize them.
● Iterations: Define the number of times you want to run the collection.
● Delay: Define the time delay (in milliseconds) between each request.
● Data: If you have any data files associated with your collection, you can
select them here.
4. Click on the "Start Run" button to run the collection.
5. Once the collection run is complete, you can view the results of each
request in the Collection Runner window. You can view the response
data, headers, and status codes for each request.
6. You can also export the results of the collection run as a JSON file or a
CSV file.

Overall, the Collection Runner is a powerful tool that allows you to test and
automate your API requests in a systematic and efficient manner.
4

How to upload & download files using Rest Assured?

In this example, the cookie is added to the request header using the cookie()
method, and the response is verified using the statusCode() and body() methods.
import static io.restassured.RestAssured.given;

import Java.io.File;

import io.restassured.response.Response;

public class FileUploadExample {

public static void main(String[] args) {

File file = new File("path/to/file.txt");

Response response = given()


.multiPart("file", file)
.when()
.post("https://example.com/upload");

System.out.println(response.getStatusCode());
}
}

In this example, we're using the multiPart method to upload a file. The multiPart
method takes two parameters: the name of the form field (file in this case)
and the file object.

To download a file, you can use the Response.getBody() method:

import static io.restassured.RestAssured.given;

import Java.io.FileOutputStream;
5

import Java.io.IOException;
import Java.io.InputStream;
import Java.io.OutputStream;

import io.restassured.response.Response;

public class FileDownloadExample {

public static void main(String[] args) throws IOException {

Response response = given()


.when()
.get("https://example.com/download");

InputStream inputStream = response.getBody().asInputStream();


OutputStream outputStream = new
FileOutputStream("path/to/output.txt");

int read;
byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {


outputStream.write(bytes, 0, read);
}

outputStream.close();
inputStream.close();
}
}

In this example, we're using the Response.getBody() method to get the response
body as an input stream. We then write the input stream to a file using an
output stream. Note that we're using a buffer (bytes) to read and write the file
in chunks of 1024 bytes, which helps to conserve memory.

Image
6

What is serialization & deserialization in Java and REST


Assured?

Serialization is like packing your favorite toy into a box so you can give it to

your friend who lives far away. You put it in the box and wrap it up so it

doesn't get damaged, and then send it to your friend. When your friend

receives the box, they can open it up and see your toy just like you packed it.

Deserialization is like when your friend receives the box with your toy inside.

They unwrap it and take the toy out of the box. The toy is just like how you

packed it and they can play with it just like you did.

Similarly, in computers, serialization is like packing data into a format that can

be easily transmitted or stored, while deserialization is like unpacking that

data back into its original form so that it can be used again.

Serialization and deserialization are concepts that are used to convert data structures or

objects into a format that can be easily transmitted over a network or stored in a file, and

then to convert that data back into its original form.

In Java, serialization and deserialization are achieved through the Java.io.Serializable

interface, which is implemented by classes that need to be serialized or deserialized. The

process of serialization involves converting an object or data structure into a stream of


7

bytes, which can then be transmitted or stored. The process of deserialization involves

converting the byte stream back into the original object or data structure.

Rest Assured is a testing library for RESTful web services, and it also supports serialization

and deserialization of objects. Rest Assured uses the ObjectMapper class from the Jackson

library to perform serialization and deserialization.

To serialize an object using Rest Assured, you can use the given().body() method and pass

the object as an argument. Rest Assured will automatically serialize the object to JSON

or XML, depending on the content-type of the request.

Here's an example of serializing an object using Rest Assured:

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class SerializationExample {

public static void main(String[] args) {

MyObject myObject = new MyObject();


myObject.setName("John");
myObject.setAge(30);

RestAssured.given()
.contentType(ContentType.JSON)
.body(myObject)
.post("https://example.com/api/myobject");
}
}
In this example, we're serializing the MyObject object and sending it as the

request body to the https://example.com/api/myobject endpoint using a POST

request.
8

To deserialize a response using Rest Assured, you can use the

Response.getBody().as() method and pass the class of the object you want to

deserialize to as an argument. Rest Assured will automatically deserialize the

response body to an object of the specified class.

Here's an example of deserializing a response using Rest Assured:

import io.restassured.RestAssured;
import io.restassured.response.Response;

public class DeserializationExample {

public static void main(String[] args) {

Response response = RestAssured.get("https://example.com/api/myobject/123");

MyObject myObject = response.getBody().as(MyObject.class);


System.out.println("Name: " + myObject.getName());
System.out.println("Age: " + myObject.getAge());
}
}
In this example, we're deserializing the response body from the

https://example.com/api/myobject/123 endpoint into a MyObject object. We then print

the values of the name and age fields of the object.

TestNG

TestNG:

https://automationreinvented.blogspot.com/2021/01/top-60-interview-questions-on.h

tml
9

● Testng.xml design techniques


● Suite in testing - YES
● TestNG annotations along with real-time scenarios
● Retry listeners setup for framework YES
● Parallel Execution Using TestNG - YES
● Important TestNG annotations - YES
● Soft Assertions - YES
● Usage of Groups to create Automation Suite - YES

TestNG is a popular testing framework used in Java applications to perform


unit, functional, and integration testing. It allows developers to create and
execute tests with ease and provides various features like grouping tests,
parallel execution, and more.

When it comes to designing a TestNG test suite using the testng.xml file,
there are various techniques that can be used to ensure that the tests are
well-organized and easy to manage. Here are some of them:

1. Grouping tests: TestNG allows you to group tests based on their


functionality, priority, or any other criteria. This can be done using the
@Test annotation or by creating groups in the testng.xml file. Grouping

tests allows you to run only specific tests or groups of tests when
required, reducing the overall test execution time.
2. Using parameters: TestNG allows you to pass parameters to your test
methods using the @Parameters annotation. This can be done in the
testng.xml file by defining the parameter values and passing them to
the test methods. Using parameters allows you to run the same test
with different inputs, reducing the need for duplicate tests.
3. Test dependency: TestNG allows you to define test dependencies using
the dependsOnMethods attribute. This ensures that certain tests are run
10

only after the required tests have passed. Test dependencies help in
ensuring that the tests are executed in a specific order, preventing any
unnecessary failures.
4. Parallel execution: TestNG allows you to run tests in parallel, either at
the method level or the suite level. This can be done using the parallel
attribute in the testng.xml file. Parallel execution allows you to reduce
the overall test execution time by running tests simultaneously.
5. Data providers: TestNG allows you to use data providers to pass data to
your tests. This can be done using the @DataProvider annotation or by
defining the data provider in the testng.xml file. Using data providers
allows you to run the same test with different sets of data, reducing the
need for duplicate tests.

By using these techniques, you can design a TestNG test suite that is
well-organized, easy to manage, and reduces the overall test execution time.

How to create suites using testNG ?

Create a new XML file and define your test suite in it. You can do this by using
the <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> declaration and
defining your suite with the <suite> tag.

1. Inside the <suite> tag, define the classes you want to include in your
suite using the <classes> tag.
2. Within the <classes> tag, define the class you created in step 1 using the
<class> tag.
11

3. Save your XML file and run it using TestNG. You can do this by
right-clicking on the file and selecting "Run as TestNG Suite".

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Automation Regression Suite">

<test name="API TestCases">

<classes>

<class name="api.com.tests.apiTestScript" />

</classes>

</test>

</suite>

https://testng.org/doc/documentation-main.html

How to create test suites using Class?

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="API Automation Session Smoke Suite">
<test name="API Users TestCases">
<classes>
<class name="userManagement.getUsers" />
12

<class name="userManagement.getPostmanEcho" />


</classes>
</test>
</suite>

How to create test suites using Package?

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="API Automation Session Smoke Suite">
<test name="API Users TestCases">
<packages>
<package name="userManagement"/>
</packages>
</test>
</suite>

How to create test suited using Groups ?

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="API Automation Session Smoke Suite">

<test name="API Users TestCases">

<groups>

<run>
13

<include name="RegressionSuite"/>

</run>

</groups>

<classes>

<class name="userManagement.getUsers" />

<class name="userManagement.getErgast" />

</classes>

</test>

</suite>

Parallel TestNG Execution for Classes?

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">


14

<suite name="API Automation Session Smoke Suite" parallel="classes"


thread-count="1">

<test name="API Users TestCases">

<classes>

<class name="userManagement.getUsers" />

<class name="userManagement.getPostmanEcho" />

</classes>

</test>

</suite>

Parallel TestNG Execution for Tests

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="API Automation Session Smoke Suite" parallel="tests"


thread-count="2">

<test name="Automation Test Get Users">

<classes>
15

<class name="userManagement.getUsers"/>

</classes>

</test>

<test name="Automation Test Postman Echo">

<classes>

<class name="userManagement.getPostmanEcho"/>

</classes>

</test>

<test name="Automation Test Postman">

<classes>

<class name="userManagement.getErgast"/>

</classes>

</test>

</suite>
16

Soft Assertions in TestNG

package com.amazon.business.utils;

import org.testng.asserts.SoftAssert;

public class SoftAssertionUtil {


private SoftAssert softAssert;

public SoftAssertionUtil() {
softAssert = new SoftAssert();
}

public void assertTrue(boolean condition, String message) {


try {
softAssert.assertTrue(condition, message);
} catch (AssertionError e) {
softAssert.fail(message);
}
}

public void assertEquals(Object actual, Object expected, String


message) {
try {
softAssert.assertEquals(actual, expected, message);
17

} catch (AssertionError e) {
softAssert.fail(message);
}
}

public void assertNotEquals(Object actual, Object expected, String


message) {
try {
softAssert.assertNotEquals(actual, expected, message);
} catch (AssertionError e) {
softAssert.fail(message);
}
}

public void assertAll() {


softAssert.assertAll();
}
}

softAssertionUtil.assertTrue(page.CURATION_HEADER.isPresent(),
" Header should be present");
softAssertionUtil.assertTrue(page.CURATION_MESSAGE.isPresent(),
" Message should be present");
softAssertionUtil.assertAll();
18

Soft Assert vs Hard Assert


https://automationreinvented.blogspot.com/2020/11/difference-between-soft-assert-a
nd-hard.html

Parameters & dataprovider with TestNG


here is an example of how to use TestNG parameters in Rest Assured:

Let's say you have an API endpoint that takes two parameters, id and name,
and returns some data. You want to test this endpoint with different values
for id and name. You can use TestNG parameters to achieve this:

1. Define a data provider method in your test class that returns a


two-dimensional array of objects. The first dimension represents the
different sets of parameter values, and the second dimension
represents the individual parameter values. For example:

@DataProvider(name = "testdata")
public Object[][] testData() {
return new Object[][] {
{"1", "John"},
{"2", "Jane"},
{"3", "Bob"}
};
}
2. In your test method, use the @Test annotation with the dataProvider
attribute to specify the data provider method and the @Parameters
annotation to specify the parameter names. For example:

@Test(dataProvider = "testdata")
@Parameters({"id", "name"})
public void testEndpoint(String id, String name) {
19

given()
.param("id", id)
.param("name", name)
.when()
.get("/endpoint")
.then()
.statusCode(200);
}

In this example, the testdata data provider method returns three sets of
parameter values: 1 and John, 2 and Jane, and 3 and Bob. The testEndpoint test
method is annotated with @Test(dataProvider = "testdata"), which tells TestNG to
use the testdata data provider method to provide the parameter values. The
@Parameters({"id", "name"}) annotation specifies that the parameter values

should be mapped to the id and name parameter names.

When you run this test, TestNG will execute the testEndpoint test method three
times with the different parameter values provided by the testdata data
provider method. This allows you to test the same API endpoint with different
parameter values without duplicating the test code.

RetryListener

When writing API automation tests with Rest Assured, it is not uncommon to

encounter flaky tests. These are tests that sometimes pass and sometimes

fail, even though the system under test has not changed. The most common

causes of flaky tests are network issues, server overload, and race conditions.
20

Flaky tests can be frustrating, as they waste time and effort and can lead to

false positives or false negatives.

To address the issue of flaky tests, TestNG provides a Retry Listener that allows

tests to be retried a certain number of times if they fail. The Retry Listener can

be used in API automation with Rest Assured to automatically retry failed

tests, which can increase the stability and reliability of the test suite.

Here are some of the benefits of using a Retry Listener in API automation

with Rest Assured:

1. Reduced false positives and false negatives: By retrying failed tests, the

likelihood of false positives and false negatives is reduced. This means

that the test results are more reliable and accurate.

2. Increased stability: Retry listeners help to stabilize the test suite by

making it less sensitive to network issues, server overload, and race

conditions. By retrying failed tests, the test suite can adapt to changing

system conditions and produce more consistent results.

3. Faster feedback: Retry listeners can help to reduce the time it takes to

get feedback on the test results. Instead of having to rerun failed tests

manually, the Retry Listener can automatically retry them, which saves

time and effort.

Overall, using a Retry Listener in API automation with Rest Assured can help

to improve the stability and reliability of the test suite, reduce false positives

and false negatives, and provide faster feedback on the test results.
21

Link

Extent Report

Extent Reports is an open-source reporting library useful for test


automation. It can be easily integrated with major testing
frameworks like JUnit, NUnit, TestNG, etc. These reports are HTML
documents that depict results as pie charts.
How to integrate extent report:
https://automationreinvented.blogspot.com/2021/05/how-to-integrate-extent-reporti
ng-to.html

How to install jenkins server in windows, mac and linux

machine with official links?

Sure! Here are the steps to install Jenkins server on Windows, Mac, and Linux machines,

along with the official links for each platform:

Windows:

1. Download the Jenkins installer from the official website:

https://www.jenkins.io/download/

2. Run the installer as an administrator and follow the installation wizard.

3. Choose the recommended plugins to install, or select the plugins you need.

4. Create an admin user account and password.

5. Configure the Jenkins URL and port number.

6. Start the Jenkins service.


22

Mac:

1. Install Homebrew, a package manager for macOS, if you haven't already. You can

follow the instructions here: https://brew.sh/

2. Open Terminal and run the command "brew install jenkins".

3. Wait for the installation to complete.

4. Start the Jenkins service with the command "brew services start jenkins".

5. Open a web browser and go to "http://localhost:8080" to access the Jenkins web

interface.

Linux:

1. Open a terminal window and update the package manager with the command

"sudo apt update".

2. Install Jenkins with the command "sudo apt install jenkins".

3. Wait for the installation to complete.

4. Start the Jenkins service with the command "sudo systemctl start jenkins".

5. Open a web browser and go to "http://localhost:8080" to access the Jenkins web

interface.

Note that the installation steps may vary depending on the specific version of Windows,

Mac, or Linux you are using, as well as the Jenkins version. You can refer to the official

Jenkins documentation for more detailed instructions on installing Jenkins on your

specific platform: https://www.jenkins.io/doc/book/installing/


23

How use spec builder

Spec builders in Rest Assured allow you to define the request and response

specifications for your API tests. Here are the steps to use spec builders in

Rest Assured:

1. Import the necessary packages:

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;

2. Create a RequestSpecBuilder and set the request details:

RequestSpecBuilder requestSpecBuilder = new RequestSpecBuilder();


requestSpecBuilder.setBaseUri("https://your-api.com"); requestSpecBuilder.setBasePath("/api");
requestSpecBuilder.addHeader("Authorization", "Bearer your-token");

3. Create a RequestSpecification from the RequestSpecBuilder:

RequestSpecification requestSpec = requestSpecBuilder.build();

4. Create a ResponseSpecBuilder and set the response details:

ResponseSpecBuilder responseSpecBuilder = new ResponseSpecBuilder();


responseSpecBuilder.expectStatusCode(200);
responseSpecBuilder.expectContentType("application/json");
responseSpecBuilder.expectBody("data.id", equalTo(1234));

5. Create a ResponseSpecification from the ResponseSpecBuilder:


24

ResponseSpecification responseSpec = responseSpecBuilder.build();

6. Use the RequestSpecification and ResponseSpecification in your API

tests:

given() .spec(requestSpec) .when() .get("/users/1234") .then() .spec(responseSpec);

In this example, we are using the request and response specifications to

make a GET request to the /users/1234 endpoint and verifying that the

response matches our expectations.

Using spec builders can help you write cleaner and more maintainable API

tests by separating the request and response details from the test logic.

READ JSON ARRAY

Example
First of all, let us create a JSON document with name sample.json with the 6
key-value pairs and an array as shown below −

{
"ID": "1",
"First_Name": "Sidharth Shukla",
"Last_Name": "Bhagavatula",
"Date_Of_Birth": "1989-09-26",
"Place_Of_Birth":"Vishakhapatnam",
"Salary": "25000"
"contact": [
"e-mail: [email protected]",
"phone: 9848022338",
"city: Hyderabad",
"Area: Madapur",
"State: Telangana"
25

]
}

To read an array from a JSON file using a Java program −

Instantiate the JSONParser class of the json-simple library.

JSONParser jsonParser = new JSONParser();


Parse the contents of the obtained object using the parse() method.

//Parsing the contents of the JSON file


JSONObject jsonObject = (JSONObject) jsonParser.parse(new
FileReader("E:/players_data.json"));
Retrieve the value associated with a key using the get() method.

String value = (String) jsonObject.get("key_name");

Just like other element retrieve the json array using the get() method into the
JSONArray object.

JSONArray jsonArray = (JSONArray) jsonObject.get("contact");


The iterator() method of the JSONArray class returns an Iterator object using
which you can iterate the contents of the current array.

//Iterating the contents of the array


Iterator<String> iterator = jsonArray.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}

OR
26

for (int i = 0; i < languages.length(); i++) {


String language = languages.getString(i);
System.out.println(language);
}

Following Java program parses the above created sample.json file, reads its
contents and, displays them.

Example

import Java.io.FileNotFoundException;
import Java.io.FileReader;
import Java.io.IOException;
import Java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class ReadingArrayFromJSON {
public static void main(String args[]) {
//Creating a JSONParser object
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new
FileReader("E:/test.json"));
//Forming URL
System.out.println("Contents of the JSON are: ");
System.out.println("ID: "+jsonObject.get("ID"));
System.out.println("First name: "+jsonObject.get("First_Name"));
System.out.println("Last name: "+jsonObject.get("Last_Name"));
System.out.println("Date of birth: "+ jsonObject.get("Date_Of_Birth"));
System.out.println("Place of birth: "+ jsonObject.get("Place_Of_Birth"));
System.out.println("Salary: "+jsonObject.get("Salary"));
//Retrieving the array
JSONArray jsonArray = (JSONArray) jsonObject.get("contact");
System.out.println("");
27

System.out.println("Contact details: ");


//Iterating the contents of the array
Iterator<String> iterator = jsonArray.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Output

Contents of the JSON are:

ID: 1

First name: Sidharth Shukla

Last name: Bhagavatula

Date of birth: 1989-09-26

Place of birth: Vishakhapatnam

Salary: 25000

Contact details:

e-mail: [email protected]

phone: 9848022338

city: Hyderabad
28

Area: Madapur

State: Telangana

Fetch data from an array

"books": [ Java, JavaFX, Hbase, Cassandra, WebGL, JOGL]

}
import Java.io.File;
import Java.io.IOException;
import Java.nio.file.Files;
import org.json.*;

// Read the JSON file into a String


String jsonString = new String(Files.readAllBytes(new
File("path/to/your/file.json").toPath()));

// Parse the JSON string into a JSONObject


JSONObject json = new JSONObject(jsonString);

// Access the "books" array and print each item


JSONArray books = json.getJSONArray("books");
for (int i = 0; i < books.length(); i++) {
String book = books.getString(i);
System.out.println(book);
}

You might also like