Where we learn technology

Category: Uncategorised (Page 1 of 7)

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 2020 – 4:30 PM IST)

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

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 2020.

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, 2020 
Duration: 9 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)
  • 6 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 6-7 weeks. It can take more than this also.

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 AutomationLa

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:

3. How to write Selenium WebDriver Test with TestNG – Maven Project

You might be wondering when Selenium WebDriver itself is such a powerful web automation tool, why do we need TestNG. Well, the fact is that it is indeed a powerful automation tool, however it lacks various capabilities such as ability to group, parameterize, sequence and generate reports. This is where tools like TestNG and JUnit come into play. These tools have inherent capabilities to organize and execute scripts as per the need of different test phases, arrange and execute them in a logical sequence as needed per the business requirements.

In the previous section, we have seen how to use TestNG with simple Java project. In this section let us see with Selenium WebDriver project in Eclipse IDE.

Step1. Go to Eclipse IDE, right click on the Package Explorer, select New and Click on Project option.

Step 2. You will see New Project window, select Maven Project and click on Next button

Step3. Select ” Create a simple project (skip archetype selection)” and click on next button.

Step 4: Provide Group ID, Artifact ID, Name and Description as shown in the below screenshot

Step 5. Click on Finish button.

Maven creates the Project structure as shown in the below screenshot

Step 6. Maven reads pom.xml file and executes the project. Pom.xml is the file which contains project and configuration details such as dependencies, build directory, plugins, goals etc. to build the maven project. So we need to add TestNG and Selenium WebDriver jar files’ details in the dependency section as shown below.

You might notice that we have added one more dependency i.e, webdrivermanager. Let’s quickly see what is the WebDriverManager.

You probably know that in Selenium Webdriver, to use browsers such as Chrome, Firefox, Safari etc., first we need to download the driver i.e, a binary file that allows WebDriver to handle browsers. And we should set the path of these files in the code as shown below

System.setProperty(“webdriver.chrome.driver”,”/path/to/chromedriver”);

System.setProperty(“webdriver.gecko.driver”,”/path/to/firefoxdriver”);

In addition to this, we need to check manually when the new version of the driver binaries released. WebDriver manger has automated this process for us to overcome this manual process. We just have to add the dependency and include the code as shown below.

WebDriverManager.chromeDriver().setup();

WebDriverManager.firefoxDriver().setup();

Step 6. We also need to add TestNG library in the Java build path. Let’s do it.In the Package Explorer, select the project, right click on it. Then go to Properties->Java Build Path->Add Library-> Select TestNG-> Next->Finish.

Note : All dependency jar files are downloaded in “Maven Dependencies” folder in the Project directory.

Step7. Now we are good to write the code. Remember all our TestNG, test related code goes in the src/test/java folder. We can either create a new Java class or a TestNG Class.

To create Java class, right click on the folder-> new ->Java class->Give a class name and click on Finish.

To Create TestNG class,right click on the folder->Others->select TestNG class as shown below

Provide the details and select the required annotations in the New TestNG class window as shown below and click on Finish button.

If you have created Java project, you need to write the required annotation along with Selenium Webdriver methods. If you have created the TestNG class along with required annotations, you might have to rearrange the annotations as per your testing needs. In additon to this, you can also include other annotations if needed. Let’s see a sample code.

Step 1. Create two class files called SeleniumTestNGDemoTest.java and BaseTest.java files .Write codes to verify “Sign in” link and “Google Search “button in the Google webpage.

Step2: Go to BaseTest.java, write Selenium WebDrivercode code to initialize the WebDriver, launch the browser and navigate to the Google Website. These are pre-test condition to execute the test cases. Also write one post-test condition, i’e, to close the browser as shown below.

Step 3: Go to SeleniumTestNGDemoTest.java, write the selenium code for the above mentioned test cases. Refer the below screenshot for the same.

Step 4. Create a testng.xml file as shown below and run the testng.xml file. If you don’t know how to execute the TestNG projects, please refer my earlier article.

In the Console, you can see that it is executed successfully.

Also, you can check status of the test cases that are passed, failed or skipped in the Results tab as shown below.

The report generated will be saved in the index.html under test-output folder. You can refresh and check this folder. In the next article, we will see how to prioritize the test cases and then understand the TestNG reports in detail.

Please follow and like us:

1. What is TestNG and How to install it

TestNG is an open source Java testing framework which is distributed under the Apache Software License and is readily available for download. TestNG is inspired by JUnit which was the most widely used testing framework for Java applications. Despite being an easy to use and straightforward framework, JUnit has its own limitations which gave rise to TestNG. It was created by Cedric Beust to simplify a broad range of testing needs.

TestNG takes care of needs across testing lifecycle including unit testing, functional testing and Integration testing etc. The “NG” in TestNG stands for ‘Next Generation” implying that, is a next generation testing framework and it is more powerful than JUnit when it comes to parallel testing, reporting and managing dependencies. This article makes an effort to elaborate the above said aspects in further details.

TestNG Features

Some of the key features include

  • Control over test execution with powerful annotations
  • Help achieve parallel testing
  • Ability to set dependencies on methods
  • Support for parameterize
  • Support for Data Driven Testing using data providers
  • Generate test logs across tests
  • Excellent reporting ability
  • Can be integrated with Eclipse, Maven, Jenkins etc

How to get started with TestNG

Before learning TestNG, you should have the basic knowledge of automation testing and any automation tools that supports Java. Here we are going to learn TestNG framework with Selenium WebDriver hence knowledge of the same is essential.

TestNG can be integrated with Simple Java project or Maven Integrated Java Project. Before we start writing the automation test scripts, let’s see the steps involved to automate the testcases and its execution.

Step 1: Write the business logic of your test

Step 2: Insert TestNG Annotations in your test code to control the flow of test cases to follow the business logic

Step 3: Validate test cases with TestNG assertion

Step 4: Add details of testcases in the testNG.xml file

Step 5: Run your Tests

Step 6: View the results in HTML reports

We are going to create Java project and integrate TestNG, hence make sure Jdk1.8 and Eclipse IDE is installed in your machine. Note:The example shown are written and executed in Windows 10, 64 bit system.

How to install TestNG

Generally, TestNG comes as jar files. There are two ways of installing TestNG in Eclipse.

  1. Directly from the Eclipse Marketplace
  2. Through Help -> Install New Software option

How to Install TestNG through Market place

This option is available in new versions of Eclipse. This is the recommended method as it is the easiest method to install TestNG compared to the other installation method.

Step 1: Launch Eclipse IDE, click on the Help menu, select the “Eclipse Market place…” option in the dropdown

Step 2:  In Eclipse Marketplace dialog box, you see “Find” input field, enter “TestNG” and hit the enter key to search.

Step3: Now, you’ll see “Install” button for all search results. Click on “Install” button of TestNG for Eclipse as shown in the above screenshot and proceed with the installation . It will take some time ..so be patient ;).

Step 4: Click on “I accept the terms of the license agreement” and then click Finish.

Step 5: If you see a security warning, ignore it by clicking the OK button. 

Now, wait for the installation to finish.

Step 6: After the installation, Eclipse will prompt you to restart, just click Yes.

How to verify TestNG Installation

There are multiple ways to verify the successful installation of TestNG.

One way is to launch the Eclipse, navigate to “Preferences” from “Window” option in the menu bar, see TestNG listed. Refer the below screenshot for the same.

Another way to verify is to right click on the project in Project Explorer section, you will see TestNG listed as shown below.

How to install TestNG Plugin in Eclipse using the “Install New Software…” feature.

Step1. Launch the Eclipse IDE, Go to Help menu and click on “Install New Software”..

Step2. It will launch an Install window as shown below.

Step 3: You need to copy the build path url from the site https://github.com/cbeust/testng-eclipse. So, go to the site and copy the stable release url from Update sites’ section as shown below

Step 4: Come back to the Eclipse IDE and paste it in “Work With” input box. You will see that the TestNG option listed as shown below. Select the TestNG option and click on Next button and continue the installation process, accept the licence agreement and click on Finish button. If you see a security warning, just ignore and accept it by clicking the OK button. Once the installation is complete, Eclipse will prompt you to restart it. Click on Yes to restart.

Step 5: After the restart, to verify the successful installation of TestNG plugin follow the same procedures mentioned in the First method of installation.

 In the next section, we will see how to write TestNG code to build Test framework with simple Java and Selenium WebDriver project with Eclipse IDE.

Please follow and like us:
« Older posts