Schedule a meeting in case of any queries/guidance/counselling:
Book An Appointment
Where we learn technology
Book An Appointment
By far, the most widely used modern version control system in the world today is Git. Git is a mature, actively maintained open source project originally developed in 2005 by Linus Torvalds, the famous creator of the Linux operating system kernel.
Developers who have worked with Git are well represented in the pool of available software development talent and it works well on a wide range of operating systems and IDEs (Integrated Development Environments).
Having a distributed architecture, Git is an example of a DVCS (hence Distributed Version Control System). Rather than have only one single place for the full version history of the software as is common in once-popular version control systems like CVS or Subversion (also known as SVN), in Git, every developer’s working copy of the code is also a repository that can contain the full history of all changes.
In addition to being distributed, Git has been designed with performance, security and flexibility in mind.
4. GIT first commit
5. GIT – 2nd commit
6. GIT logs/history
7. GIT diff
8. GIT blame/ GIT short log
9. GIT local branching process
10. PR (Pull Request) Process
11. GIT various branching commands:
12. GIT Clone vs GIT Fork
13. GIT Local Merge
14. GIT Tag and Releases
15. GIT Fetch vs PULL
16. GIT Merge vs Rebase
17. GIT Cherry-Pick
18. GIT Stash
19. GIT Merge Conflict
20. GIT Aliases
21. Comparing two commits
22. GIT Reset
23. GIT Revert
Buy Now:
Grab it in just:
Discounted Price: 1299 INR (20 USD)
Actual Price: 2250 INR (30 USD)
Payment Options:
Here I’m sharing the bank account details.
Please send me the screenshot of the receipt once you make the payment without fail.
Please send the details at : naveenanimation20@gmail.comSubject Line: GIT Course Payment Receipt – Your Full Name
You can make the payment via payment link:
OR Via Bank Transfer:
Please find below bank details:
You can make the transaction directly to the given account or make it via Western Union Or Xoom.
Bank Details:
Full Name: NAVEEN KHUNTETAContact No.: 9902233400Payee name: NAVEEN KHUNTETAName of the Bank: ICICI bankAddress of the Bank: Bhandarkar Road, PuneBank Account Number: 624001553272IFSC Code(11 Digit Code): ICIC0006240You can send via PayPal or Xoom also:
PayPal Payment: https://paypal.me/naveenautomation
Xoom Payment:
https://www.xoom.com/india/send-money
You can also make the payment via Tez (Google Pay) OR PhonePe :
UPI to this number: +91-9902233400
UPI: naveenanimation20@okicici
OR Google ID: naveenanimation20@gmail.com
PING ME AT +91-9902233400, IN CASE OF ANY ISSUES.
Note:
naveenanimation20@gmail.com
Terms & Conditions:
1. For the paid course, refund is not applicable.
2. In case of any need of resume, you can mail me or tag me in Box comments section.
3. You can mail me or tag me in Box in case of any technical questions and doubts.
4. Response time of the queries within 24 hrs.
5. Technical queries won’t be resolved over whats app messages.
6. Feel free to ping me, in case of any Box issues.
7. This is strictly not allowed to share your credentials with anyone, if any account is found, it will be deactivated and account will be terminated.
Cheers!
Happy learning!
Naveen AutomationLabs
~Source: Google
Introduction:
In this Article, We are going to learn about creating UI Test automation framework with Cucumber BDD Approach.
What is BDD ?
Why Cypress ?
Cypress Project Setup with Cucumber:
To enable the cucumber preprocessor plugin:
Open cypress/plugins/index.js and this snippet
const cucumber = require('cypress-cucumber-preprocessor').default module.exports = (on, config) => { on('file:preprocessor', cucumber()) }
Add support for feature files to your Cypress configuration
cypress.json{ "testFiles": "**/*.feature" }
Add this section to your package.json:
"cypress-cucumber-preprocessor": {
"nonGlobalStepDefinitions": true
}
To bind our step definitions to our features files.
Cucumber Feature File:
A feature file can contain a scenario or can contain many scenarios in a single feature file but it usually contains a list of scenarios in English format using some BDD keywords and the language is called “Gherkin“.
Steps:
Provide Feature name, Feature Description and Type Scenario and give Scenario name.
Let’s try to understand the Feature File:
After the Scenario, we need to write certain statements with Keywords Given, When, Then, And also But.
Now, We have to create the step definition for the test written in the feature file:
Since we have feature file with us, now we have to create step definition file for the same :
and folder in left pane and step definition would look like below:
Hit the command npx cypress run and output on console will be displayed as below:
and to run in Test runner enter the command npx cypress open in the terminal and then run feature file and will be displayed as below:
Step Definitions with Dynamic Parameters:
Say, when you have to pass username and password as dynamic values below is the code snippets to be followed
Feature: Login Tests
Login Test Cases
Scenario: Login with valid credentials
Given Login to the application
When I type username as "username"
And I type password as "password"
Then click Login
And See the homepage
import { Given , And , Then , When} from "cypress-cucumber-preprocessor/steps";
Given('Login to the application', () => {
cy.visit('http://zero.webappsecurity.com/login.html')
})
When('I type username as {string}',username=> {
cy.get('#user_login').type(username)
})
And('I type password as {string}',password=> {
cy.get('#user_password').type(password)
})
Then('click Login', () => {
cy.get('input[name="submit"]').click()
})
And('See the homepage', () => {
cy.get('a:contains("Zero Bank")').should('be.visible')
})
and In the Test Runner, it will be shown as with proper Given, When, Then and And statements:
Concept of Grouping and Filtering of Test Cases/ Smart Tagging:
when you have multiple scenarios and wanted to check few test cases to run, just put @focus on the specific scenarios you want to run:
Also, you can tag your test cases with @smoke and @Regression test cases and run the particular scenarios from your command line with the below command :
./node_modules/.bin/cypress-tags run -e TAGS=’not @Smoke and (@Regression or @Sanity)’
Hooks Support in cypress and cucumber:
Let’s begin to Explore Data Driven Testing with cucumber:
Feature File:
Feature: Login Tests
Login Test Cases
Scenario: Login with multiple credentials
Given Login to the application
When I type the credentials
| uname | pword |
| username | password |
| hello | world |
Then click Login
To pass multiple test data set, you define the test set in tabular form like done above:
import { Given , And , Then , When} from "cypress-cucumber-preprocessor/steps";
Given('Login to the application', () => {
cy.visit('http://zero.webappsecurity.com/login.html')
})
When('I type the credentials',function(dataTable) {
cy.get('#user_login').type(dataTable.rawTable[1][0])
cy.get('#user_password').type(dataTable.rawTable[1][1])
cy.get('#user_login').type(dataTable.rawTable[2][0])
cy.get('#user_password').type(dataTable.rawTable[2][1])
})
Then('click Login', () => {
cy.get('input[name="submit"]').click()
})
Let’s try to understand the code:
To fetch the test data, just write dataTable in function and as I have defined 2D array, fetch first username as dataTable.rawTable[1][0] that means raw one and 0 coloumn and it will fetch username as “username”.
Generating HTML Cucumber Reports:
Add below code snippet in package.json
"cypress-cucumber-preprocessor": {
"cucumberJson": {
"generate": true,
"outputFolder": "cypress/cucumber-json",
"filePrefix": "",
"fileSuffix": ".cucumber"
}
}
and remember we have already have cypress-cucumber-preprocessor “nonGlobalStepDefinitions”: true, after that cucumberJson should be put in package.json and output will be generated under cypress/cucumber-json.
cucumber.json file:
And to create HTML report : Install this plugin with the following command:
const report = require('multiple-cucumber-html-reporter');
report.generate({
jsonDir: './path-to-your-json-output/',
reportPath: './path-where-the-report-needs-to-be/',
metadata:{
browser: {
name: 'chrome',
version: '60'
},
device: 'Local test machine',
platform: {
name: 'ubuntu',
version: '16.04'
}
},
customData: {
title: 'Run info',
data: [
{label: 'Project', value: 'Custom project'},
{label: 'Release', value: '1.2.3'},
{label: 'Cycle', value: 'B11221.34321'},
{label: 'Execution Start Time', value: 'Nov 19th 2017, 02:31 PM EST'},
{label: 'Execution End Time', value: 'Nov 19th 2017, 02:56 PM EST'}
]
}
});
Configure jsonDir and reportPath as or the way you want :
Now, we need to execute this js file to get the HTML Report , just hit the command as node cucumberHTMLReport.js
Open this file in browser to get full-fledge HTML report:
For the code reference, please clone the project from:
https://github.com/MandeepKaur2020/CypressFrameworkBDD.git
References:
Conclusion:
Blog Contributors:
Author: Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java) and Cypress. Expertise in API using Rest Assured, HTTP Client and Performance testing using JMeter.https://www.linkedin.com/in/mandeepkaur93/
Reviewer: Naveen Khunteta
https://www.linkedin.com/in/naveenkhunteta
According to worldwide Google Trends of the IT sector, the demand for well-trained API (Backend) testing professionals has increased substantially.
With the growing need of API testing, the tools and technologies are progressing hand-in-hand which focuses on improving performance, ease-of-use, reliability and accessibility.
Karate DSL is becoming a fore-runner of the tools and technologies available, fulfilling all these parameters in a short period of time.
With 4.4K GitHub stars and 1.1K GitHub forks, Karate DSL is progressively becoming popular amongst the QA community.
It is an Open Source Web-Services Test Automation Solution that integrates in a unified framework API test-automation, performance-testing and even UI automation.
It is developed on top of Cucumber-JVM, which enables us to build API-based BDD (Behaviour Driven Development) test scenarios for testing which means Gherkin becomes the primary programming language.
However, unlike the BDD framework, Karate DSL has omitted step-definition file writing efforts for the corresponding feature file i.e. we can execute the feature file comprising of all the test cases without defining step-definition file with the help of TestRunner class.
Looking at the wide range of Karate DSL features, aren’t you curious about learning and using this awesome tool?
In my forthcoming blog, let us explore Karate in depth along with its setup and configurations.
Did you find this blog informative ? Please share your views in the comment section below or you can follow me on LinkedIn.
Till then stay safe and Happy Learning !!!
Blog Contributors:
Author: Priyanka Brahmane
~ Image Source:google/.sashido.io/
Introduction
In this article, we are going to learn about the HTTP Post Method in detail and various ways to create a post payload, in addition to that, we will also learn how to validate Post Response using RestAssured.
Writing post Method
Let’s start writing our first positive scenario :
Note: Content type can be XML if you are using XML, else it would be JSON
package com.restassured.tests;
import io.restassured.http.*;
import org.apache.http.HttpStatus;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
/**
* @Author: Mandeep Kaur
*/
public class PostMethodTest {
@Test
public void sampleTest() {
// Json Body to pass in the request
String jsonBody = "{" +
" \"name\":\"Test Automation\",\n" +
" \"gender\":\"Male\",\n" +
" \"email\":\"testAutomation3@gmail.com\",\n" +
" \"status\":\"Active\"\n" +
"}";
given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f")
.accept(ContentType.JSON)
.contentType(ContentType.JSON)
.and()
.body(jsonBody)
.when()
.post("https://gorest.co.in/public-api/users") //hit the post end point
.then().
assertThat()
.statusCode(HttpStatus.SC_OK)
.and()
.body("data.name", equalTo("Test Automation")); // Match the output actual to expected
}
}
Another scenario is the negative case:
Would be if we send the same request, then it should return the response code as “422” and message as email has already been taken because to create user every time unique email should be passed:
JSON Object
Now, the other way of creating the payload/ request is through JSON Object:
A JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations.
Instead of sending the hardcode JSON body, we can send customize data along with post request.
For this scenario, what we need to do is :
Add this maven dependency in your project
After that manipulate below JSON request to JSON Object:
{
"name":"Test Automation",
"gender":"Male",
"email":"testAutomation6@gmail.com",
"status":"Active"
}
And here’s the below code for the same :
Post Request by JSONObject
package com.restassured.tests;
import org.json.JSONObject;
import org.junit.Test;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
/**
*
* @author Mandeep kaur
*
*/
public class SamplePostRestTest {
@Test
public void createUser_whenSuccess() {
JSONObject jsonObject = new JSONObject();
//insert key value pair to jsonObject
jsonObject.put("name", "Test Automation");
jsonObject.put("gender", "Male");
jsonObject.put("email", "testAutomation14@gmail.com");
jsonObject.put("status", "Active");
String resp= given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f23")
.accept(ContentType.JSON)
.contentType("application/json")
.and()
.body(jsonObject.toString())
.post("https://gorest.co.in/public-api/users") //hit the post end point
.thenReturn().asString();
System.out.println(resp);
}
}
As can be seen, We can use JSONObject and insert the values in the attribute just like hashMap in java and later on, can pass the JSON object in String. After that, validations can be performed accordingly:
And From hashMap also we can create JSON Object like below:
Map<String, String> map = new HashMap<>();
map.put("name", "Test Automation");
map.put("gender", "Male");
map.put("email", "testAutomation14@gmail.com");
map.put("status", "Active");
JSONObject jo = new JSONObject(map);
and this jo object reference can simply be passed in the request.
Since this nature of post request is quite simple, so for the complex request, you need to modify the request as per given specification.
Let’s take a small example:
[
"Employee",
{
"city": "chicago",
"name": "john",
"age": "36"
}
]
Now here it is having array and then a JSON object :
To build this request we need to have this below structure:
JSONArray jsonArray = new JSONArray();
jsonArray.put("Employee");
JSONObject jo = new JSONObject();
jo.put("name", "john");
jo.put("age", "22");
jo.put("city", "chicago");
jsonArray.put(jo);
To illustrate the example above, we first need to create the JSON object and insert values in it, once done then we need to pass this object in JSON Array which again comes from org.json package(below-detailed description of JSONArray), JSON array has its own element as “Employee” which can also be inserted using put() method and finally we can insert this JSONArray into request body like below
A JSONArray is an ordered collection of values, resembling Java’s native Vector implementation.
package com.restassured.tests;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
/**
*
* @author Mandeep kaur
*
*/
public class SamplePostRestTest {
@Test
public void createUser_whenSuccess() {
JSONArray jsonArray = new JSONArray();
jsonArray.put("Employee");
JSONObject jo = new JSONObject();
jo.put("name", "john");
jo.put("age", "22");
jo.put("city", "chicago");
jsonArray.put(jo);
given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f23")
.accept(ContentType.JSON)
.contentType("application/json")
.and()
.body(jsonArray.toString())
.post("https://gorest.co.in/public-api/users") //hit the post end point
.thenReturn().asString();
}
}
If there will be any issues with JSON Object, We will get below exception:
The JSONException is the standard exception thrown by this package whenever any error is encountered. This is used across all classes from this package. The exception is usually followed by a message that states what exactly went wrong.
Object Mapping:
Lastly, the other method where payloads can be really complexed, we can go for Object Mapping:
We need to follow below steps :
Let’s analyse the below code
{
“name”:”Test Automation”,
“gender”:”Male”,
“email”:”testAutomation6@gmail.com”,
“status”:”Active”
}
To Create the mapping class, I would say go to JSONToJavaObject, paste the JSON request and get the Mapping class. As done below:
JsonToPOJO
Mapping class
And our createUser Mapping class will look like this:
package com.restassured.vo;
public class createUserDO {
private String name;
private String gender;
private String email;
private String status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Now, the second step is to create an object of Mapping class:
package com.restassured.tests;
import org.junit.Test;
import com.restassured.vo.createUserDO;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
/**
*
* @author Mandeep kaur
*
*/
public class SamplePostRestTest {
@Test
public void createUser_whenSuccess() {
createUserDO cu = new createUserDO();
cu.setName("Test Automation");
cu.setGender("Female");
cu.setEmail("testAutomation25@gmail.com");
cu.setStatus("Active");
String resp = given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f")
.accept(ContentType.JSON)
.contentType("application/json")
.and()
.body(cu)
.post("https://gorest.co.in/public-api/users") //hit the post end point
.thenReturn().asString();
System.out.println(resp);
}
}
Note: if we need to have logs to verify things, we can simply use log().all() and it can display information on a console like below:
Logs on Console
Since we have converted our object to the body, now to validate the response we can use the process called deserialization of response body, which means converting response body to object.
To do that, the first thing is to create a mapping class for response JSON body, you use the same converter as above json2pojo schema and below code how it is to be done:
Deserialization of Response body
package com.restassured.tests;
import static io.restassured.RestAssured.given;
import org.junit.Test;
import org.testng.Assert;
import com.restassured.vo.CreateUserDO;
import com.restassured.vo.ResponseDataObjects;
import io.restassured.http.ContentType;
/**
*
* @author Mandeep kaur
*
*/
public class SamplePostRestTest {
@Test
public void createUser_whenSuccess() {
CreateUserDO cu = new CreateUserDO();
cu.setName("Test Automation");
cu.setGender("Female");
cu.setEmail("testAutomation1465@gmail.com");
cu.setStatus("Active");
ResponseDataObjects responseDataObjects = given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f")
.accept(ContentType.JSON)
.contentType("application/json")
.and()
.body(cu)
.post("https://gorest.co.in/public-api/users") //hit the post end point
.thenReturn().as(ResponseDataObjects.class);
Assert.assertEquals("Test Automation",responseDataObjects.getData().getName());
}
}
Till .post function we were clear what needs to be performed, the next step is thenReturn(), basically, to fetch the response body after that, as (the method )will take the mapping class(ResponseDataObjects ) to deserialize the response and this will return us the object of our mapping class.
And this class can be used to fetch all the information later on, for validations and verification checks.
Our JSON Response
{
"code": 201,
"meta": null,
"data": {
"id": 1493,
"name": "Test Automation",
"email": "testAutomation701@gmail.com",
"gender": "Male",
"status": "Active",
"created_at": "2021-01-07T12:30:58.987+05:30",
"updated_at": "2021-01-07T12:30:58.987+05:30"
}
}
And correspondence POJO class:
Note: we need to use @JsonIgnoreProperties(ignoreUnknown=true)as is applicable at deserialization of JSON to Java object (POJO) only
package com.restassured.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseDataObjects {
private Integer code;
private Object meta;
private Data data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public Object getMeta() {
return meta;
}
public void setMeta(Object meta) {
this.meta = meta;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
package com.restassured.vo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {
private Integer id;
private String name;
private String email;
private String gender;
private String status;
private String createdAt;
private String updatedAt;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
}
Conclusion:
In this article, we have learnt how to create a payload using various ways such as via string, JSON Object and with object Mapping and how to fetch the response using Deserialization.
Blog Contributors:
Author: Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
Reviewer: Naveen Khunteta
https://www.linkedin.com/in/naveenkhunteta
In this article, we are going to learn about the Get Request in detail, in addition to that, we will also learn how to validate Get Response using RestAssured.
2. Writing Get Method:
Let’s first get started with the simple example – Fetch user details and handle the response:
Assume application is up and running , let’s perform some action using when()
As we can see return type of when() is RequestSender ~https://javadoc.io/doc/io.rest-assured/
and RequestSender Interface Implements Classes as:RequestSpecificationImpl, TestSpecificationImpl
And in RequestSpecificationImpl class we have below methods such as get() :
Now, Let’s write the Get Method Code:
package com.restassured.testcases;
import static io.restassured.RestAssured.given;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.annotations.Test;
/**
*
* @author Mandeep Kaur
*
*/
public class SampleGetTest {
@Test
public void getTest() {
/*
* given application is up and running and performing the GET request with get(URL)
* and printing the response
*
*/
Response response =given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e19f").when()
.get("https://gorest.co.in/public-api/users");
//Printing the response
System.out.println(response.asString());
}
}
In the above code ,it is clearly seen that we need header in order to execute get request and it takes key-value pair where Key as authorisation and value as Bearer access_token , get (URL ) and simply print the response and output will be like below and stored in response object.
User details are coming in response what’s more the details of test cases if it’s passed, failed depends on the test case written:
In order to validate status code , below code needs to be executed:
package com.restassured.testcases;
import static io.restassured.RestAssured.given;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.apache.http.HttpStatus;
import org.testng.annotations.Test;
/**
* @author Mandeep Kaur
*/
public class SampleGetTest {
@Test
public void getTest() {
/*
* given application is up and running and performing the GET request with get(url)
* with header then status code should be 200 OK
*
*/
given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c12327f409a3228f205e19f").when()
.get("https://gorest.co.in/public-api/users").then().assertThat().statusCode(HttpStatus.SC_OK);
}
}
It can be inferred from the above code, if expected code is 200 ok then to validate it , we can use .assertThat and statusCode: HttpStatus.SC_OK without using 200 hard code value as it is, we can use HttpStatus interface variable from package org.apache.http; Similarly, the other statuses from Interface HttpStatus can be fetched like below:
Since, we have validated the status code, Let’s validate the response content also content level validation. Once we received the response , how we will validate that the content is proper or not ?
So, rest assured uses hamcrest Framework for validation.
Inside org.hamcrest package there is a class called Matchers and this class contains all the methods which we can be used for our validation purpose. Below are the methods of Matchers class and you can navigate here to learn more about Matchers class :
Go to Library org.hamcrest > Matchers Class> Methods
Let’s see the below code:
package com.restassured.testcases;
import static io.restassured.RestAssured.given;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.*;
/**
* @author Mandeep Kaur
*/
public class SampleGetTest {
@Test
public void getTest() {
/*
* given application is up and running and performing the GET request with get(url)
* Then response should have first email as given below
*/
given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f0394504395435").when()
.get("https://gorest.co.in/public-api/users").
then().
body("data.email[0]",equalToIgnoringCase("dhawan_dharani@macejkovic.co"));
}
}
After hitting the get endpoint , in the body we are validating whether the first email in our response matches to the given email given above in the code and here equalToIgnoringCase comes from the matches Class of hamcrest framework. what it does is where both actual value is equal to expected value irrespective of case.
If both the values matched we will get our test case passed otherwise it will failed as actual value is not getting matched with expected value.
Here’s the json response , for which our code matched perfectly:
If not matched the expected value, then we will get the error as below:
and if multiple values to be validated , we can validate like below using comma :
By now , You must be wondering why did i use data.email[0] for this we need to learn Json Path.
And another way of validating it with hasItem method of hamcrest and if it list needs to be validated then hasItems method will be used:
hasSize to use when to check how many element a particular json array contains. For Example:
"data": {
"data1":[
"id": 6,
"name": "Dharani Dhawan",
"email": "dhawan_dharani@macejkovic.co",
"gender": "Female",
"status": "Active",
]}
Now this contains 5 elements so size will be 5.
and in body we can assert :
.body(“data.data1”,hasSize(5));
3. JsonPath Class :
Another way of validating the response with JsonPath Class:
JsonPath class comes from the package
package io.restassured.path.json;
Let’s see the below code to gain deep understanding of it :
package com.restassured.testcases;
import static io.restassured.RestAssured.given;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.*;
/**
* @author Mandeep Kaur
*/
public class SampleGetTest {
@Test
public void getTest() {
/*
* given application is up and running and performing the GET request with get(url)
* Then response should have first email as given below
*/
String resp= given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f84985934850948")
.accept(ContentType.JSON)
.when().get("https://gorest.co.in/public-api/users").
thenReturn().asString();
JsonPath jsonpath= new JsonPath(resp);
Assert.assertEquals("dhawan_dharani@macejkovic.co",jsonpath.getString("data.email[0]"));
}
}
In this code, we fetched the response and store it in string variable.
Now, this variable needs to be passed as a JsonPath constructor, once this is done
we need to use testNg assertions to check our actual response is matched with expected Response.
Actual Value : given above as email
and jsonpath.getString for fetching the value of particular Key:
data.email[0] : means Json Object starts with label data and email is comes under that label and JsonPath is same like Xpath where we transverse from root element to parent /sibling so on.
Since we need out first value to be matched me just used email[0].
To fetch int or other values it can be fetched like this :
4.Conclusion:
To conclude, We learnt to write our very first get Request Method and tried to validate our response with hamcrest framework and jsonPath Class .
Blog Contributors:
Author: Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
Reviewer: Naveen Khunteta
https://www.linkedin.com/in/naveenkhunteta
1. Overview :
In this article, we will learn about automating our first API using Rest Assured and various terms linked with API.
2. API
Before proceeding any further , let’s try to understand what is API .
Why do we need API or what does it offers :
Let’s try to understand with the help of an example:
Consider an ATM Machine, you are provided with multiple options such as checking account balance, cash deposit or withdrawal and statement, etc. So here you get all things by a push of few buttons.
Here APIs play a Key Role in abstracting you from the backend services. Also performing any operations such as cash withdrawal you need to provide your ATM pin and the amount to be withdrawn.
The withdrawal would be allowed only if your pin is correct and have sufficient balance money in your account and it is within the bank transactional limit for the day. So these are some business rules defined and these are nothing but contractual obligations that an API defines and that has to be fulfilled.
So, in short, if both the business and data logic can be re-used in some other application. Then this application is called a web service.
3. Web Service:
It is an interoperable software system designed to support machine-to-machine interaction over a network. The three necessary conditions for any web application to become a web service:
Now that you have understood the web service and API, the next important term you need to understand is the API endpoint
By now you have understood that web services are capable of communicating with web applications with the help of API endpoints.
Now the question is what does this API endpoint contain that makes any web server understand the requests from the UI and how to respond back?
The two things that make it possible are the request and response that is passed with every API call.
So now it’s imperative to understand how request and response exchange takes place between a client (Browser) and a server
You must have heard the terms SOAP and Rest, Let’s try to understand these first in detail:
4.SOAP Architecture:
So today many applications built in many programming language . For example there is web applications designed in JAVA, some are in .dot net and some in PHP.All these
So this is where SOAP or Simple Object Access Protocol comes into the picture.
Here are a few reasons for using SOAP architecture:
Some limitations with SOAP architecture such as:
5. Rest Architecture:
Let’s look at some characteristics of the REST architecture:
6. HTTP Protocol:
We have talked a lot about HTTP protocol, but we still don’t know what exactly is this HTTP or even protocol for that matter.
So, whenever you enter any URL in the address bar of your browser, the browser translates that URL into a request message according to the specified protocol and then sends it to the server.
There are many predefined HTTP methods that can be used while sending HTTP requests.
Most common HTTP methods:
Then there are two different categorisation of HTTP methods:
The response from the server is accompanied by a status code. This status code is important as it tells the client how to interpret the server response. Here are some of the common status codes –
Some of the common HTTP status are:
Further, you can read about what happens when you type a URL and press enter.
Till now we have learned about API, Web Services, SOAP and Rest, HTTP protocol, and methods, Now it’s the perfect time to know about Rest Assured.
7.Rest Assured:
8. Creating a simple Rest Assured Program:
Pre-requisites:
JDK 8 , Maven, Eclipse IDE
Let’s get started by creating the first project. Open Eclipse IDE and create a new project.
2. Provide group id and Artifact id and click on finish:
Now , configure testNg and Rest Assured library in your pom File:
Once , libraries are added then create a class under src/test/java and create a test method in it:
Here’s the code:
package com.restassured.testcases; import org.testng.annotations.Test; import io.restassured.http.ContentType; import static io.restassured.RestAssured.*; /** * * @author Mandeep Kaur * */ public class SampleTest { @Test public void sampleLogin() { /* * Given application is up and running When i perform the GET request using the * given url Then the status code should be 200 Ok And the response body should * be in Json Format * */ given().accept(ContentType.JSON).header("user-key", "cde67df2673438bb2fae8dc7e205e98451903940394343").when() .get("https://developers.zomato.com/api/v2.1/categories").then().statusCode(200); } }
Before concluding let’s understand few above terms quickly:
and now run the project using mvn install command and output will be displayed as:
Conclusion:
To encapsulate, we have learned about API and it’s various terminologies, also created our first rest assured test 🙂
Blog Contributors:
Author: Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
Reviewer: Naveen Khunteta
https://www.linkedin.com/in/naveenkhunteta
Selenium & Java Training – Regular Batch (6th December 2023)
This time I’m introducing some amazing content on Java, Selenium and some different approaches on Framework Designing with some really complex real time use cases.
This will be a very different content from my YouTube channel.
After a very high demand on Java+Selenium, here I’m going to start next batch (8:30 AM IST / 10:00 PM EST / 7 PM PST / 9 PM CST) from 6th December 2023.
Next Batch Starting from: 6th December, 2023
Duration: 15 weeks (4 days in a week) (Mon to Thursday)
Total Fee:
17,000 INR (for Candidates in India) – including Registration Fee
320 USD (for Candidates in USA/UK/AUS/Europe) – including Registration Fee
Location: Online (Zoom Meeting) – 1 hr + 15 mins
Note:
There will be 2 demo sessions (first two classes are demo sessions).
Demo Meeting link will be shared one day before the session.
After 2 demo sessions, pending amount must be paid.
Please fill this training registration form after making the payment.
Note: If you are paying through PayPal, You need to pay 330 USD (10 USD will be the PayPal Fee).
Imp Note:
Course Content:
2) Core Java/Programming : This class will set you up for understanding Basic OOPs and java concepts. These concepts will be extremely important for you to become a good Automation tester. This section is specially designed so that can be followed by any Manual test very easily.
3) Eclipse IDE : This topic might seem little off place here but it’s very important topic to understand the tool you are using. Eclipse will the primary choice of development environment and we will discuss features of eclipse here.
17) Dev Ops & Continuous Integration
19). Docker
Cheers!!
Naveen AutomationLa
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
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 |
© 2023 naveen automationlabs
Theme by Anders Norén — Up ↑