Where we learn technology

Category: Uncategorised (Page 1 of 7)

Building a Test Automation Framework Using Cypress with Cucumber

 
 

 

 

                                          ~Source: Google

Introduction:

In this Article, We are going to learn about creating UI Test automation framework with Cucumber BDD Approach.

What is BDD ?

  • Behaviour-driven development is an Agile software development process that fosters collaboration between developers, software testers, and the non-technical, business side in a software development process.
  • It asserts how an application should behave from the end user’s perspective.

Why Cypress ?

  • Front end testing tool built for the modern web applications.
  • Because of its Architectural design, Cypress delivers fast, consistent and reliable test execution compared to other Automation tools
  • Cypress takes snapshots as your tests run. We can hover over each command in the Command Log to see exactly what happened at each step. 
  • Cypress automatically waits for commands and assertions before moving on. 
  • Ability to test edge test cases by Mocking the server response.

Cypress Project Setup with Cucumber:

  • Download Node js from https://nodejs.org/en/download/ as per your operating system, as the cypress is built on the node js.
  • Create a folder and import the folder in any editor atom, sublime or visual studio code and open the terminal.
  • Setup a new npm package : npm init, this will create package.json in your project.
  • Open the terminal and enter npm install cypress cypress-cucumber-preprocessor, this will install cypress and cucumber in your project.
  • Dependencies should get added in package.json file.
  • Execute a command npx cypress open and you will be displayed with these folders in editor’s Left Pane.

Editor Left Pane

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:

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:

  • Create a folder under the Integration folder as CucumberTests
  • Create a file login.feature and click login.feature and type Feature and the syntax for the same will get poped up automatically:

Type Feature in feature file

Provide Feature name, Feature Description and Type Scenario and give Scenario name.

Feature File

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. 

  • Given: It describes the pre-requisite for the test to be executed.
  • When: It defines the trigger point for any test scenario execution.
  • Then: It holds the expected result for the test to be executed.
  • And: It provides the logical AND condition between any two statements
  • But: It signifies logical OR condition between any two statements.

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 :

  • Create a folder login, remember folder name should be the same as the name of feature file. 
  • login.feature is the feature file name and folder should have name as login
  • Under the login folder, create a loginSteps.js file and start Mapping the test steps with feature file test cases.

and folder in left pane and step definition would look like below:

Step Definition in loginSteps.js

Hit the command npx cypress run and output on console will be displayed as below:

Output after Running feature file

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:

Test Runner when passed Dynamic values

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:

@focus on 1st sceanrio

and it skips the other test case in Test Runner.

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:

  • The cypress-cucumber-preprocessor supports both Mocha’s before/beforeEach/after/afterEach hooks and Cucumber’s Before and After hooks.
  • Cucumber Before hooks run after all Mocha before and beforeEach hooks have completed and the Cucumber After hooks run before all the Mocha afterEach and after hooks.
  • As we are using Mocha test framework with cucumber and cypress, it’s always good to go with Mocha hooks.

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:

login.cucumber.json

And to create HTML report : Install this plugin with the following command:

  • npm install multiple-cucumber-html-reporter –save-dev
  • Add cucumberHTMLReport.js file under your parent project and paste the below code:

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

Output for HTML Report

Open this file in browser to get full-fledge HTML report:

HTML Report with Features, Scenarios and Run info with how total test cases, passed, failed state.

 

For the code reference, please clone the project from:

https://github.com/MandeepKaur2020/CypressFrameworkBDD.git

References:

Conclusion:

In this write up, we learnt about how to create test automation framework using cypress with cucumber and generated some good HTML Reports.

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

 

 

 

 

Please follow and like us:

A Quick Introduction About Karate DSL

Bonjour TestCommunity!!! 

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

Why Karate DSL is the best tool for API Automation ?

Karate DSL is becoming a fore-runner of the tools and technologies available, fulfilling all these parameters in a short period of time.

Courtesy: Karate logo

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.

In addition to these benefits, there are numerous points of interest recorded below:

  • Karate DSL uses english-like language – Gherkin.
  • Powerful JSON & XML assertions along with “deep-equals” payload assertions. 
  • You do not need to write additional “glue” code or Java “step definitions” Java. 
  • Parallel execution feature offered by Karate in turn reduces the test execution time. Hence, making it a very fast API testing tool
  • For large responses, data validation becomes easier by “match” keyword.
  • Data-driven tests that can also use sources from JSON or CSV
  • Even for non-programmers, tests are simple to write, i.e. it is based on the common Cucumber / Gherkin standard with syntax colouring options.

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

Priyanka is an Automation tech enthusiast having an industry expertise of more than 6 years with a special bent for Karate DSL and Web Automation.
 
She is a staunch believer in the “one is always a learner” theory.
She can be connected on LinkedIn and follow me on Medium.
 
Reviewer: Naveen Khunteta
https://www.linkedin.com/in/naveenkhunteta/
Please follow and like us:

HTTP POST Method Using RestAssured

 

                      ~ 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 :

  1. Given Accept the given content in JSON format
  2. with content type as JSON
  3. and Body
  4. when I performed the Post Request
  5. Then status Code should be 200 OK
  6. And The response should have name as given in JSON body

 

Code with Positive test case

  • As depicted in the screenshot, Primarily, to hit the JSON HTTP post request we need to have JSON Body and passing the JSON body as a string in Body function would suffice our need.
  • This means, once we have the body, we can simply pass our endpoint here in the .post function and once it is successful, we need to assert whether we get the expected output or not.
  • Below is the code for same:

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:

Code with negative test case when an email is already existing

JSON Object

Now, the other way of creating the payload/ request is through JSON Object:

JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations.

  • Keys are unique Strings that cannot be null
  • Values can be anything from a Boolean, Number, String, JSONArray or even a JSONObject.NULL object
  • A JSONObject can be represented by a String enclosed within curly braces with keys and values separated by a colon, and pairs separated by a comma
  • It has several constructors with which to construct a JSONObject

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

Json Dependency

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

JSONArray is an ordered collection of values, resembling Java’s native Vector implementation.

  • Values can be anything from a Number, String, Boolean, JSONArray, JSONObject or even a JSONObject.NULL object
  • It’s represented by a String wrapped within Square Brackets and consists of a collection of values separated by commas
  • Like JSONObject, it has a constructor that accepts a source string and parses it to construct a JSONArray

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:

 

JSON 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 :

  • Create a Mapping class also called POJO class (Plain Old Java Objects) and this process is called serialization as we are going to convert the object to the body.
  • Create an object of Mapping class
  • Initialise the values available in the mapping class
  • Send the object along with post request

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:

  • createUserDO cu = new createUserDO();
  • Initialised the values via setters i.e setName(“Test Automation”) available in the mapping class.
  • and finally, we sent the object in the post call

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);

             }
	}

POST Method via Mapping class

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

Please follow and like us:

HTTP GET method using RestAssured

Get Request And Response
~Image Source : google / sashido.io

  1. Introduction

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:RequestSpecificationImplTestSpecificationImpl

And in RequestSpecificationImpl class we have below methods such as get() :

Get Methods

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:

Output on the console and test case is passed and marked as green.

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

Matchers Class under org.hamcrest package

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:

Json Response

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:

HasItem Method

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 :

Extracting Values from jsonPath

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 :


Fetch values from jsonPath

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

 

 

 

 

Please follow and like us:

Introduction To Rest Assured

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 .

  • API: Application Programming Interface is nothing but public functions that can be called and executed by other programs, these other programs can be programs running in the same computer or those running in a different computer altogether.

Why do we need API or what does it offers :

  1. Abstraction 
  2. Contractual Obligations between client and backend

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:

  1. Interoperability: Any Java, DotNet, PHP, or C++ application, etc.., should be able to interact with the web application.
  2. Application-to-application interaction: For example, Jet Airways in its web application uses a different bank’s payment gateway to make payments. Here, banks have extended their applications over the network to be accessed by the jet airways application. Thus, the bank application is acting as a web service.
  3. Communication must be over a network

Now that you have understood the web service and API, the next important term you need to understand is the API endpoint

  1. It is a location from which an API can access the resource that it needs to carry out the functionality.
  2. It is a unique URL for communications between the client-side and server-side.

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 

  • Application collect and store data, and this data needs to be exchanged among different applications.
  • But this exchange among these heterogeneous applications would be very complex.
  • So, one of the methods to combat this complexity is to bring a common language which is XML i.e. Extensible Markup Language
  • But there for no specific standard on how to use XML across all the programming language for data exchange

So this is where SOAP or Simple Object Access Protocol comes into the picture.

Here are a few reasons for using SOAP architecture:

  1. SOAP is considered a light-weight protocol that is used by applications for data exchange. Also, since SOAP is particularly based on XML, which in itself is a lightweight data exchange language, so it falls in the same category as a protocol.
  2. SOAP is designed to be platform and operating system independent. It can work with programming languages on both Windows and Linux platforms.
  3. It is based on the  HTTP protocol, which is the default protocol used by all web applications. Therefore, there is no customization required to run the web services built on the SOAP protocol to work on the World Wide Web.
  4. It helps in Exposing business functionality over the internet.

 Some limitations with SOAP architecture such as:

  1. The HTTP protocol is not used to its full extent.
  2. A resource representation is done only in XML which is fast, but still can be considered slower than many of its competing technologies such as JSON.
  3. Working with SOAP requires you to write a proper XML structure almost every time, even for extremely simple tasks. This makes your work lengthy and a bit complex.
  4. The above-mentioned limitations can overcome with the introduction of REST(Representational State Transfer) architecture.

5. Rest Architecture:

Let’s look at some characteristics of the REST architecture:

  1. It makes the best use of the HTTP protocol. The request and response sent are proper HTTP request and response. So, the request contains proper HTTP methods while the response contains proper status codes.
  2. It is a style for designing loosely-coupled web services.
  3. It relies on the stateless, client-server protocol, for example, HTTP. So, it does not store any client’s session on the server-side and thus making the REST APIs less complex to develop and maintain.

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:

  1. GET :asks the server to retrieve a resource. You can think of a resource as some data or file on the server
  2. POST : asks the server to create a new resource
  3. PUT: asks the server to update a resource
  4. DELETE: asks the server to delete a resource
  5. PATCH: used to update a portion of an already existing resource

Then there are two different categorisation of HTTP methods:

  1. Safe: Safe methods are those that can be cached and prefetched without any repercussions to the resource. This means that there is no change expected in the resource by the client. So, GET is safe, while PUT, POST, DELETE PATCH are not.
  2. Idempotent: An idempotent HTTP method is one that if called many times will provide the same outcome. It does not matter if the method is called only once or multiple times. The result will always be the same. GET, PUT, DELETE methods are idempotent.

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 –

  1. 1XX – informational
  2. 2XX – success
  3. 3XX – redirection
  4. 4XX – client error
  5. 5XX – server error

Some of the common HTTP status are:

  1. 201 (CREATED)
  2. 200 (OK)
  3. 401 (UNAUTHORIZED)
  4. 403 (FORBIDDEN)
  5. 400 (BAD_REQUEST)
  6. 404 (NOT_FOUND)

Figure: Sending a Request and getting the Response

Further, you can read about what happens when you type a URL and press enter.

https://medium.com/@maneesha.wijesinghe1/what-happens-when-you-type-an-url-in-the-browser-and-press-enter-bb0aa2449c1a

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:

  • REST Assured is an open-source Java library for validation of REST web services.
  • It is flexible and easy to use and supports all the Http Methods such as GET, POST, PUT, etc.
  • It supports BDD (Behavior-Driven Development) by using test notation, Given, When, and Then, which makes the tests human readable.
  • Rest Assured API uses the “Hamcrest” framework for validation.Which we will learn it in detail

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.

  1. Click on new –> Maven Project → create simple project → Next

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:

    • Rest Assured framework follows the BDD approach.
    • Given keyword defines the precondition
    • When keyword defines the action to be performed
    • Then keyword defines the outcome of the previous step
    • And keyword defines the additional outcome.
    In the above program, the Given application is up and running, the header is passed with a valid user key when performing the GET request using the given URL Then the status code should be 200 Ok And the response body should be in JSON Format (ContentType.Json)

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

 

 

 

 

Please follow and like us:

Selenium & Java Training Course Content – Regular Evening Batch (15th March 2021 – 4:30 PM IST) (Registration is closed now)

Selenium & Java Training – Regular Evening Batch (15th March 2021)

(Registration is closed now)

Hi Folks,

Please enrol ASAP.  🙂 This time I’m introducing some amazing content on Java, Selenium and some different approaches on Framework Designing. This will be very different from my YouTube channel.

After a very high demand on Java+Selenium training,

Here I’m going to start next batch (4:30 PM to 5:45 PM IST – 1hr 15 mins) from 15th March 2021.

Thanks for registering “Selenium & Java Sessions” By Naveen AutomationLabs. As per the further registration process, you need to pay the 3000 INR (50 USD for US Folks) as a registration fee.

Next Batch Starting from: 15th March, 2021 
Duration: 11 weeks

Registration Fee: 3000 INR (50 USD)
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 (Goto Meeting)

ClassesTimings: (3 Days in a week – Monday – Wed – Friday)

  • 4:30 PM IST (Indian Time)
  • 11 AM (UK Time)
  • 7 AM EST (US Time)

Note:

 Payment Options:

Here I’m sharing the bank account details. Please send me the screenshot of receipt once you make the payment without fail. 
You need to mail me at : naveenanimation20@gmail.com

Please find below bank details: You can make the transaction directly to the given account or make it via Western Union (only via bank transfer) Or Xoom.

Bank Details:

Name:  MANALI GUPTA

To Account: 256010100095576
Account Type : Savings

Bank Name: AXIS BANK

City: GUJARAT

Branch Location: PALANPUR, GUJRAT

IFSC Code: UTIB0000256

PayPal Payment: 

  • If you are paying through PayPal, You need to pay 330 USD (10 USD will be the PayPal Fee).
  • Use this PayPal id: https://paypal.me/NaveenKhunteta

For Candidates in India:

You can also make the payment via Tez (Google Pay) :
UPI to this number: +91-9902233400. 
UPI: naveenanimation20@okicici 
OR Google IDnaveenanimation20@gmail.com

Note:

  • There will be 2 demo sessions. In case If you don’t like the sessions or if you want to leave. Full Registration amount will be transferred back to you after 2 sessions.
  • After 2 demo sessions, pending amount must be paid.
  • I’ll share the meeting id with URL to join the session before the training everyday.

Course Content:

Selenium WebDriver is a leading web automation testing tool in industry. It is one of the most popular tool. Selenium WebDriver jobs are on a rise and are highly paid and highly valued. Industry is shifting towards automation rapidly.

Today, every start up, product based and service based companies need Automation QA Engineer to automate their web apps.

With more and more applications becoming accessible through browser it becomes very important to learn Selenium WebDriver.

This course is designed to teach in depth concepts of Selenium WebDriver 3 and Java. We focus on the basics first and then move towards the advance concepts of Selenium, Java and framework development.

Part -1: Basics of Java & Selenium

1) Automation : A brief introduction to automation and the need for automation. How automation will enable you to beat competition and make you get the better jobs in market.
• What is Automation Testing
• Use of automation Testing
• Tools for Automation Testing
• Why automation is important for you career?
• What is Selenium
• Advantage of Selenium
• Introduction to WebDriver

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.

  • Data Types and Variables
  • String Class
  • Arithmetic Operators & Concatenation operators
  • Conditional & Decision Making
  • Single Dimensional Array
  • Loops (For, While)
  • Classes and Objects
  • Class Constructors
  • Functions in Java
  • Function Input Parameters
  • Function Return Types
  • Exception Handling
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Data Hiding
  • Method Overloading
  • Method Overriding
  • Abstract class
  • Interface
  • Super/This Keywords
  • Final/Finally/Finalize Keywords
  • Wrapper Classes
  • String Manipulation
  • Collections Basics (Array List, HashMap, Set)
  • Interview Questions

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.
• How to use Eclipse
• How to run, stop, pause
• How to debug in Eclipse
• Understanding console output
• How to put a break point
• How to add Watch variables
• How to find errors from Problem window
• Usage of step into and Step over debug functionality

  • Interview Questions

4) Set up Eclipse : We will start with setting up WebDriver, so that every participant start flaunting off their newly learnt skills by writing some cool test programs:
• Download and install java
• Download and start Eclipse
• Download and configure WebDriver java client
• Set up a project
• Create packages
• Create a First Java test case
• Import WebDriver Source file

  • Interview Questions

5) WebDriver Interface : This topic will make you familiar with the concept of browsers in WebDriver and how to launch basic Firefox browser using WebDriver. Here we will also talk about WebDriver & WebElement interface which will enable us to answer many complicated Interview Questions about WebDriver Implementation.
• Architecture of WebDriver
• WebDriver Interface
• WebElement Interface
• Launching Firefox/Chrome/Safari

  • Interview Questions

6) Browser & Navigation Commands : This is something which everybody do very first thing when they learn Selenium. Opening & closing of browser and some navigation function on top of it.
• How to Open a URL
• Verify Page title
• Strategy to get the Page Source 
• Difference between Close & Quit
• Ways to Navigate Back & Forward
• How to Refresh Page
• Another way of Navigating to specific Page

  • Interview Questions

7) WebElement Commands : An important and basic need of Selenium Automation. This part enables every participant to start writing automation test in their organizations. These are the most commonly used operations on any website.
• Difference between FindElement & FindElements
• Enter & Clear text from Input field
• How Click action works differently on different elements
• Managing Input fields, Buttons & Links
• Finding all links on the Page
• Extracting More than one object from a page 
• Extracting Objects from a specific area of a web page 
• Check if element is Present, Displayed, Enabled or Selected

  • Interview Questions

8) Locators : In this class we will start learning about HTML, how elements are defined inside HTML document and what are the different attributes that are associated with an HTML element. We also try to find elements based on its attribute values.
• What are locators
• HTML Basics
• HTML language tags and attributes 
• ID, Name, Xpath, CSS etc
• Difference between Absolute & Complete Xpath
• Finding your first element
• WebElement Commands

  • Interview Questions

9) Element Identification : This part explains the lifesaver Add-Ons & tools for Selenium. Finding elements are the most common activity carried out in Selenium. These tools give us power to easily identify complex elements and help us in saving lot of time.
 Element Inspector in Mozilla, Chrome and IE
• Element locator tool for FF
• Various HTML locator strategies
• XPath Helper Plug-in for Chrome
• Selection of Effective XPath
• Handling Dynamic objects/ids on the page

  • Interview Questions

10) Tables, Checkboxes & Radio buttons : Many applications involve use of web tables and list boxes. These skills will help participant to get the expertise on complex tables structures and write effective automation test.
• Identify table rows and columns
• Extracting values from a cell
• Dynamically Identify Tables Data
• Select class in Selenium
• Drop Down Handle
• Select multiple values from the list
• Select & Deselect operations by Index, Value & Visible Text

  • Interview Questions

11) Selenium Waits, Alert & Switch Windows : A little complexity will start now onwards. To use Waits effective is very important for every automation tester. Wait helps us in switching windows, handling pop-ups, operating alerts correctly.
• Implicit and Explicit waits
• How to use Expected Conditions with Waits
• PageLoadTimeout & SetScriptTimeout property
• Simple use of Thread Sleep
• Concept of Fluent Wait in Selenium 
• Strategy to poll for an object
• WebDriverWait and its uses 
• Different WaitUntil Conditions 
• Managing Ajax based components 
• Ways to handle Simple, Confirmation & Prompt Alert
• Concepts of Set Interface in Java 
• Difference between Window Handle & Handles 
• Switching & Closing Windows, Tabs & PopUps
• Concept of window ID 
• Extracting window IDs with Selenium Object reference

  • Interview Questions

12) Action Class
This gives us power on recently build Application with latest and complex object features. Hovering mouse or simulate Mouse and Keyword operations can be done by using Action Class. A necessary thing to learn in Selenium journey.
• What is Action Class & What can we do with Action Class
• Mouse Hover & Mouse Movement with Action
• Finding Coordinates of a Web Object
• Drag and Drop Action

  • Interview Questions

13) Browser Profile: Different types of browser profiles and user authentication models with examples will be discussed in this class. You will need these to test secured websites and user authenticated websites.
• What is Browser Profile
• How to set up ChromeOptions and Firefox Options

Part -2: Advanced Selenium

14) TestNG Framework
TestNG is a wonderful off the shelf framework that can be used directly to create your test framework. We will learn about this framework here.
• What is TestNG
• Benefits and Features of TestNG
• How to download TestNG
• Annotations in TestNg
• How to run Test Suite in TestNG
• Groups in TestNG
• Depend On in TestNG
• Test Case sequencing in TestNG
• TestNG Reporters
• TestNG Assets
• TestNG Parameters
• Multi Browser testing in TestNG
• Parallel testing in TestNG

  • Interview Questions

15) Automation Framework
This class will cover the concepts of Frameworks. After this the participant would got to know that which type of Framework works best for their Application and the pros & cons of the selected framework. Knowledge of frameworks is key skill to learn.
• What is Automation Framework
• Features of Automation Framework
• Benefits of using Automation Framework
• Different types of Automation Framework
• What is Data Driven Framework

  • What is Hybrid Framework
  • What is Page Object Model Design Pattern with Page Factory and Non Page Factory with OOP concepts
  • Interview Questions 

16) Real Time Live PROJECT – Selenium Hybrid Framework (POM)
In this class we will explore some major frameworks by looking at the code and understanding the key component of the framework.
A real time web application will be taken and framework will be built on top of that which will simulate actual project scenarios.

  • Introduction and Component of Frameworks
    • Designing Test Data Provider (Excel)
    • Designing Run Data Provider (Text/Property file) 
    • Setting up Maven Build Tool
    • Data Provider Design
    • Creating Page Objects & Object repository
    • Writing Test Script and Fetching Test Data
    • Designing Test Runner for Framework
    • Asserts, Test Fails & Error logging
    • Reporters, TestNG Listeners and Log file Generation
    • Running test with different Test Data
    • Generating the HTML reports : Extent Report, Allure Report, TestNG Report 

17) How to create project JARs (Generic Jars used by different teams)

  • Normal library JAR
  • How to add generic JAR as a build path in your Java Project
  • How to add generic JAR as maven dependency in POM.xml in your Maven Project
  • How to create libraries with FAT Jars and deploy it to Maven Nexus location

18) Dev Ops & Continuous Integration

  • Jenkins Setup Basics
  • Running Script via Jenkins
  • Jenkins PipleLine – Classic View
  • Jenkins PileLine – Blue Ocean
  • Jenkins PipeLine Syntax
  • Jenkins Report Generation using Extent Report, Allure, TestNG Report and Tesults Report
  • Git WebHook with NgRok to trigger the build automatically
  • GIT Repo/GIT HUB
  • Learn how to use commit command
  • What is cloning in GIT
  • My First Code Check-in to GIT
  • GIT PULL Request Process
  • GIT CheckOut
  • GIT Branching
  • GIT Merge
  • GIT Commit
  • GIT ADD
  • GIT Push, Fetch & Pull Commands

19). Docker

  • What is Docker
  • What is Docker Container
  • How to create account on Docker Hub
  • Selenium Grid Configuration on Docker Hub
  • Run your test cases on Dockerized Selenium Grid Hub – Node setup
  • Setup Infrastructure using Docker Compose yml 
  • Scale up the browsers at the run time
  • Shut down the Docker Infrastructure
  • Zalenium – Docker GRID Setup
  • Zalenium Live Preview
  • Zalenium Test Dashboard
  • Selenoid Dockerized GRID

20). AWS – Amazon Web Services – 

  • Introduction
  • Setup Account
  • Create new EC2 Instance on AWS
  • Create AMI, Security Group, VPC and Subnets
  • Selenium Dockerized GRID Setup on AWS – EC2 machine
  • Run Selenium test cases on AWS machine

 

21) Life Time Access on all recorded Videos, Free Code Repos, and Java Code

From my previous batch candidates, most of the students either got promoted  to test automation or got their dream automation jobs.  


Frequently Asked Questions:


Q1: Can I get all the recordings for these sessions?
Ans: Yes, you will get all the recordings daily basis for the specific topic.

Q2: Is this training useful for freshers?
Ans: 100% useful for freshers, who are looking for to start their career into automation QA field.

Q3: Is this training useful for Manual Testers?
Ans: 100% useful for Manual QA folks, it will surely help to trigger your interest from manual QA to Automation QA. After this training, you will become an expert in automation. 

Q4: Can I justify my automation experience, after this training?
Ans: Yes, training is designed like this only. You can easily justify 2 to 6 yrs of exp in automation after this training.

Q5: Can I crack selenium interviews after this training?
Ans: Yes, 100% guarantee. 

Q6: What is the duration of this course?
Ans: I never compromise in training content and syllabus. It depends how exactly we are going with this training. Ideally it should take 11+ weeks.

Q7: Who will be the trainer?
Ans: Only Naveen from Naveen AutomationLabs.

Q8: Will this training be different from existing YouTube videos?
Ans: Yes, it will be more in-depth training and more topics will be covered with different scenarios.

Q9: What if I miss any session?
Ans: You will get each session recording daily basis. You can cover that topic after watching the recordings. 

Q10: Will assignments be shared for covered topics?
Ans: for almost every topic, I have assignment and it will be shared daily basis. You need to submit the assignment daily basis and feedback will be shared with you regular basis.

Q11: Can I improve my programming skills after this training?
Ans: I am 100% sure, it will drastically improve your coding skills and logical thinking for writing the best optimized code.

Q12: How will you cover the topics? Is it only theory or any real time experience?
Ans: I always relate the topics with real time scenarios only, how exactly test automation and any system works and I hardly copy paste the code. I strongly prefer to write the code during the session. No COPY PASTE. NO Power Point Slides, No Boring Theories.

In case of any questions: Feel free to ping me on whats app : +91-9902233400.

Thanks for enrolling for Java and Selenium Training – By Naveen Automation Labs.

This batch is different from other previous batches, as I have some more new content in Java and Selenium with new style of framework designing part and much more.

I’m sure you will learn a lot of new things from this training. “A lot to know – A lot to learn”.

This course is huge and we really need to maintain the pace of the course, so that you all can learn the things within the given time frame. We never compromise in terms of content and quality of the training.

Few important points to remember before joining the training session:

  1. It will be online training and sessions will be recorded daily basis. Please try to join before 5-10 mins of the session time.
  2. I want you to be on mute during the session so that session should not get disturbed due to any background noise. Otherwise, it will break my rhythm as well as it will disturb the entire class.
  3. If you have any questions, you can ask in goto meeting chat section. If you have any background noise, please don’t unmute yourself. Please attend these sessions at a quite place with good internet connectivity and with good headphones.
  4. Best option is to write your question/query in chat section. I always believe, if it’s a pin drop silence, classroom decorum will be maintained properly.
  5. After the session, recording will be shared by EOD – daily basis.
  6. You can access these recordings with Life Time Access. Downloading of the videos are strictly not allowed.
  7. It’s strictly not allowed to share these videos with anyone, if it is found, the respective candidate account will be terminated immediately.
  8. It’s not allowed to create any whats app/telegram group for this training batch. If you have any suggestions or feedback, feel free to reach me out. I would love to hear from you.
  9. Session will be there for 60 mins (+10 mins extra sometimes).
  10. We will have two demo sessions, if you don’t want to continue with the sessions, registration money will be refunded back.
  11. After demo sessions, pending amount has to be paid as per the fee structure.

“Happy Learning” 🙂

Cheers!!
Naveen AutomationL

Please follow and like us:

NoSuchElementException and NotFoundException in Selenium || Common Exceptions in Selenium

There is no ElementNotFoundException as such in selenium, if you are talking in #Selenium context. We have NotFoundException which is extended by :
Direct Known Subclasses as:
NoAlertPresentException, NoSuchCookieException, NoSuchElementException, NoSuchFrameException, NoSuchWindowException

Please refer this Java API Doc: https://jar-download.com/artifacts/org.seleniumhq.selenium/selenium-api/3.141.59/documentation

NoSuchElementException extends NotFoundException” 

and 

NotFoundException extends WebDriverException“. 

This is thrown when???
1. Element could not be found in the DOM – or may it never. exists.
2. The page is still being loaded and you’ve already finished your WebElement search
3) AJAX Element has not returned yet on the page

If you encounter this exception, you may want to check the following:
>Check your selector used in your find_by…
>Element may not yet be on the screen at the time of the find operation, (webpage is still loading) apply WebDriverWait() for an element to be appeared on the page. 

Exceptions that may happen in all the webdriver code.

Common Exceptions in Selenium:

exception selenium.common.exceptions.ElementClickInterceptedException

(msg=Nonescreen=Nonestacktrace=None)[source]

The Element Click command could not be completed because the element receiving the events is obscuring the element that was requested clicked.

exception selenium.common.exceptions.ElementNotInteractableException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when an element is present in the DOM but interactions with that element will hit another element do to paint order

exception selenium.common.exceptions.ElementNotSelectableException (msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when trying to select an unselectable element.

For example, selecting a ‘script’ element.

exception selenium.common.exceptions.ElementNotVisibleException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when an element is present on the DOM, but it is not visible, and so is not able to be interacted with.

Most commonly encountered when trying to click or read text of an element that is hidden from view.

exception selenium.common.exceptions.ErrorInResponseException

(responsemsg)[source]

Thrown when an error has occurred on the server side.

This may happen when communicating with the firefox extension or the remote driver server.

exception selenium.common.exceptions.ImeActivationFailedException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when activating an IME engine has failed.

exception selenium.common.exceptions.ImeNotAvailableException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine.

exception selenium.common.exceptions.InsecureCertificateException

(msg=Nonescreen=Nonestacktrace=None)[source]

Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate.

exception selenium.common.exceptions.InvalidArgumentException

(msg=Nonescreen=Nonestacktrace=None)[source]

The arguments passed to a command are either invalid or malformed.

exception selenium.common.exceptions.InvalidCookieDomainException 

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when attempting to add a cookie under a different domain than the current URL.

exception selenium.common.exceptions.InvalidCoordinatesException

(msg=Nonescreen=Nonestacktrace=None)[source]

The coordinates provided to an interactions operation are invalid.

exception selenium.common.exceptions.InvalidElementStateException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when a command could not be completed because the element is in an invalid state.

This can be caused by attempting to clear an element that isn’t both editable and resettable.

exception selenium.common.exceptions.InvalidSelectorException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression and it is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. “count(//input)”).

exception selenium.common.exceptions.InvalidSessionIdException

(msg=Nonescreen=Nonestacktrace=None)[source]

Occurs if the given session id is not in the list of active sessions, meaning the session either does not exist or that it’s not active.

exception selenium.common.exceptions.InvalidSwitchToTargetException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when frame or window target to be switched doesn’t exist.

exception selenium.common.exceptions.JavascriptException

(msg=Nonescreen=Nonestacktrace=None)[source]

An error occurred while executing JavaScript supplied by the user.

exception selenium.common.exceptions.MoveTargetOutOfBoundsException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when the target provided to the ActionsChains move() method is invalid, i.e. out of document.

exception selenium.common.exceptions.NoAlertPresentException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when switching to no presented alert.

This can be caused by calling an operation on the Alert() class when an alert is not yet on the screen.

exception selenium.common.exceptions.NoSuchAttributeException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when the attribute of element could not be found.

You may want to check if the attribute exists in the particular browser you are testing against. Some browsers may have different property names for the same property. (IE8’s .innerText vs. Firefox .textContent)

exception selenium.common.exceptions.NoSuchCookieException

(msg=Nonescreen=Nonestacktrace=None)[source]

No cookie matching the given path name was found amongst the associated cookies of the current browsing context’s active document.

exception selenium.common.exceptions.NoSuchElementException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when element could not be found.If you encounter this exception, you may want to check the following:

  • Check your selector used in your find_by…
  • Element may not yet be on the screen at the time of the find operation, (webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait() for how to write a wait wrapper to wait for an element to appear.

exception selenium.common.exceptions.NoSuchFrameException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when frame target to be switched doesn’t exist.

exception selenium.common.exceptions.NoSuchWindowException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when window target to be switched doesn’t exist.

To find the current set of active window handles, you can get a list of the active window handles in the following way:

exception selenium.common.exceptions.RemoteDriverServerException

(msg=Nonescreen=Nonestacktrace=None)[source]

exception selenium.common.exceptions.ScreenshotException

(msg=Nonescreen=Nonestacktrace=None)[source]

A screen capture was made impossible.

exception selenium.common.exceptions.SessionNotCreatedException

(msg=Nonescreen=Nonestacktrace=None)[source]

A new session could not be created.

exception selenium.common.exceptions.StaleElementReferenceException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when a reference to an element is now “stale”.

Stale means the element no longer appears on the DOM of the page.Possible causes of StaleElementReferenceException include, but not limited to:

  • You are no longer on the same page, or the page may have refreshed since the element was located.
  • The element may have been removed and re-added to the screen, since it was located. Such as an element being relocated. This can happen typically with a javascript framework when values are updated and the node is rebuilt.
  • Element may have been inside an iframe or another context which was refreshed.

exception selenium.common.exceptions.TimeoutException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when a command does not complete in enough time.

exception selenium.common.exceptions.UnableToSetCookieException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when a driver fails to set a cookie.

exception selenium.common.exceptions.UnexpectedAlertPresentException

(msg=Nonescreen=Nonestacktrace=Nonealert_text=None)[source]

Thrown when an unexpected alert is appeared.

Usually raised when when an expected modal is blocking webdriver form executing any more commands.

exception selenium.common.exceptions.UnexpectedTagNameException

(msg=Nonescreen=Nonestacktrace=None)[source]

Thrown when a support class did not get an expected web element.

exception selenium.common.exceptions.UnknownMethodException

(msg=Nonescreen=Nonestacktrace=None)[source]

The requested command matched a known URL but did not match an method for that URL.

exception selenium.common.exceptions.WebDriverException

(msg=Nonescreen=Nonestacktrace=None)[source] vBase webdriver exception.

 

Reference taken from: 

https://www.selenium.dev/selenium/docs/api/py/common/selenium.common.exceptions.html

Cheers!!

Naveen AutomationLabs

Please follow and like us:

TestNG

Please follow and like us:
« Older posts