Example : Create Dynamic Json using javax and json – Automation Testing – RestAssured Know As Java JsonGenerator

Creating Json dynamic is always big help for automation testing. All RestAPI testing always need Json file or create Json dynamic. It is highly requirement to create dynamic Json and pass to API. Creating dynamic Json file is always good help for automation testing.

To Create/Read/Update Json , We will use Javax.json and json.simple.parser.

json-Generator
dynamic =Json-Generator

Maven :

<dependency>
  <groupId>com.googlecode.json-simple</groupId>
  <artifactId>json-simple</artifactId>
  <version>1.1.1</version>
</dependency>

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
</dependency>

Continue reading “Example : Create Dynamic Json using javax and json – Automation Testing – RestAssured Know As Java JsonGenerator”

How selenium automation framework can be easy with Reflection API in java

When you want to use keyword driven framework it is necessary to have knowledge of Reflection API in Java because in keyword driven framework we will use Reflection API

If we just focus on keyword then reflection means to reflect. Now we will see what to reflect ?

Suppose that you have a string variable number and it may have value “first” or “second” or “third”.

Now suppose we have total three methods named “first” , “second” , “third”.
So you can see that whatever value a string may have with the same value we have a method.

So now string variable number may have any value out of 3 values and suppose we want to call same method as number variable contains. For ex. If number = “second” then we want to call second().

Of course you can do this by if else if conditional statement but it is not a proper way to deal with a situation like this as you may end with 100+ condition for each scenario / test case. So we use reflection.

Reflection API will reflect whatever value contained in number variable call that method. So that’s it is Reflection.

See below code for Reflection Syntax :-

String number = "second";
        
Method method = Reflaction_Demo.class.getMethod(number, String.class);
method.invoke(method, "Hello Reflaction");

public static void second(String str)
{
    System.out.println("Second is called");
}

See For this code you need to import below :-

java.lang.reflect.Method

Study code  first we first we have found method using getMethod() function and it has two arguments but is not fixed. In parameter of this first write String that contains name of your method like in our case it in number and then write that method’s parameter details like our second() method has one String parameter so we have written String.class if there is another parameter like int i then we can add another Integer.class after String.class. So in this way you need to write parameter of your method.

Now after that we have invoked or called that method and we need to pass parameter value here like I have passed “Hello Reflection” and str variable will receive this value.

In keyword driven frame we will take one method for each action that can be taken on web element like click , write in textbox and then we will store these method names in excel sheet and read these names in java code and will call these methods in sequence.

We are using this Reflection API in many selenium automation step. Just keep eye on it

The complete code is below and you can download source code from Attachments at the end of page :

import java.lang.reflect.Method;

public class Reflaction_Demo {

    public static void main(String[] args) throws Exception {
        
        String number = "second";
        
        Method method = Reflaction_Demo.class.getMethod(number, String.class);
        method.invoke(method, "Hello Reflaction");

    }
    
    public static void first(String str)
    {
        System.out.println("One is called");
    }
    
    public static void second(String str)
    {
        System.out.println("Second is called");
    }
    
    public static void third(String str)
    {
        System.out.println("Third is called");
    }

}

How to use ArrayList in Selenium Web driver?

ArrayList is a class and you can sat it dynamic or re-sized array. If you are not aware of ArrayList and its methods then Click Here

Now when you are automation using Selenium Java there might be a situation when you need to find more than one web elements which is under another web element. For ex. There may be a
div tag which has many hyper link and you might need to find all these hyper links.

See below code to get hyper links under a div tag :-

WebElement we_div = wd.findElement(By.xpath("xpath of div or parent tag"));
        
List<WebElement> al = new ArrayList<WebElement>();
        
al = we_div.findElements(By.tagName("a"));

The complete code is below and you can download source code from Attachments at the end of page :

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ArrayList_Selenium
{    
    @Test
    public void test()
    {
        WebDriver wd = new FirefoxDriver();
        
        wd.get("url of website");
        
        WebElement we_div = wd.findElement(By.xpath("xpath of div or parent tag"));
        
        List<WebElement> al = new ArrayList<WebElement>();
        
        al = we_div.findElements(By.tagName("a"));
        
        al.get(0).click();
    }
    
}

or you can write for loop to click on all the links

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ArrayList_Selenium
{    
    @Test
    public void test()
    {
        WebDriver wd = new FirefoxDriver();
        
        wd.get("url of website");
        
        WebElement we_div = wd.findElement(By.xpath("xpath of div or parent tag"));
        
        List<WebElement> al = new ArrayList<WebElement>();
        
        al = we_div.findElements(By.tagName("a"));
        
       for(int i=0; i<al.size();i++){

        al.get(i).click();

         } 
    }
    
}

Different methods for creating xpath for selenium web driver : IMP Interview Question

Selenium Web driver will help you to do all the automation task like click,select and writing. To perform that action you need to provide details of that attribute. How you want to perform that action. One of the common method is providing xpath. Creating xpath is also important task in selenium automation. This post will help you to understand how you can create xpath for selenium web driver.

Method – 1 :-
If any web element has an id attribute then you can easily create xpath of that web element using below method :-

//*[@id=’id of that web element’]

Method – 2 :-
If web element has some text and create xpath using text here you can do like this

Suppose a hyper link has some text like “Selenium Script” and you want to create xpath for it then use below :-

//a[text()=’Selenium Script’]

You can also write like this :- //a[contains(text(),’Selenium’)]

Method – 3 :-
May be you have a web element whose id is partially changing every time you load a page. For ex. An input tag has id=selenium-1234 but when you reload a page it becomes selenium-4556 and every time you reload a page it gonna changes. So we know that prefix selenium is not changing then to find xpath of that web element see below :-

//input[starts-with(@id, ‘selenium’)]

If suffix is static then you can use like below :-

//input[ends-with(@id, ‘selenium’)]

How to take value from excelsheet in selenium automation ? STEP BY STEP

You can read values from excelsheet and use that value for selenium automation test. for ex. You can store username and password in excelsheet and read those values in your test and then you can execute your test with those values.

For this purpose you need to add some jars and there are two ways that you can get those jars as described below :-

Option – 1 :-

1) Click Here to get commons-io-2.4.jar.
2) Click Here to get poi-3.9.jar.
3) Click Here to get poi-ooxml-3.9.jar.
4) Click Here to get dom4j-1.6.1.jar.

Option – 2 :-

You can add below dependencies in your pom.xml of your maven project :-

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
 
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
 
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
 
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

Now  I did  java programming to get value from excelsheet for selenium automation test. You will able to fetch values from an excel sheet. You will get this Excel_File_Reader.java in attachments. Attachment content all the code with excelsheet. Just follow step and run. Feel free to contact us.

You need to initialize this class as show in below code :-

Excel_File_Reader excel_file_reader = new Excel_File_Reader("path to your .xlsx file");

Now you can get number of rows and number of columns as shown in below code :-

System.out.println("Rows are :- "+excel_file_reader.getRowCount("Name of sheet in your excel file"));
        
System.out.println("Columns are :- "+excel_file_reader.getColumnCount("Name of sheet in your excel file"));

You can read data in excel file using getCellData() method and you need to pass 3 values to this method and these 3 values are given below :-
1) Name of sheet in excel file.
2) Column name in that sheet.
3) Row number in that sheet

For ex. I have Sheet named “Demo” and in that I have two columns named “Usename” and “Password” then you can these values as shown in below code :-

String username = excel_file_reader.getCellData("Demo", "Username", 2);
String password = excel_file_reader.getCellData("Demo", "Password", 2);

Here row number is 2 because we know that in first row we have written label for column names.

You can also read multiple values using for loop as show below code but for now just see this as just for knowledge :-

for(int i=0 ; i< excel_file_reader.getRowCount("HalfEvent_front_end_Login") ; i++)
{
    // fetch required values here
}

Now we have username and password so we can write our test and use these values as shown in below code :-

WebDriver wd = new FirefoxDriver();
        
wd.get("http://facebook.com");
        
        
WebElement username_txtbox = wd.findElement(By.xpath("//*[@id='email']"));
username_txtbox.sendKeys(username);
        
WebElement password_txtbox = wd.findElement(By.xpath("//*[@id='pass']"));
password_txtbox.sendKeys(password);
        
WebElement login_btn = wd.findElement(By.xpath("//*[@id='u_0_n']"));
login_btn.click();

The complete code is below and you can download source code from Attachments at the end of page :

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Grab_Excel_Value
{
    @Test
    public void test()
    {
        try
        {
        Excel_File_Reader excel_file_reader = new Excel_File_Reader("/home/rocku14/Desktop/HalfEvent.xlsx");
        
        System.out.println("Rows are :- "+excel_file_reader.getRowCount("HalfEvent_front_end_Login"));
        
        System.out.println("Columns are :- "+excel_file_reader.getColumnCount("HalfEvent_front_end_Login"));
        
        String username = excel_file_reader.getCellData("HalfEvent_front_end_Login", "Username", 2);
        String password = excel_file_reader.getCellData("HalfEvent_front_end_Login", "Password", 2);
        
        // to fetch multiple values write below code
        /*
        for(int i=0 ; i< excel_file_reader.getRowCount("HalfEvent_front_end_Login") ; i++)
        {
            // fetch required values here
        }
        */
        
        System.out.println("Username is "+username);
        System.out.println("Password is "+password);
        
        WebDriver wd = new FirefoxDriver();
        
        wd.get("http://facebook.com");
        
        
        WebElement username_txtbox = wd.findElement(By.xpath("//*[@id='email']"));
        username_txtbox.sendKeys(username);
        
        WebElement password_txtbox = wd.findElement(By.xpath("//*[@id='pass']"));
        password_txtbox.sendKeys(password);
        
        WebElement login_btn = wd.findElement(By.xpath("//*[@id='u_0_n']"));
        login_btn.click();
        
        }
        catch(Exception e)
        {
            System.out.println("Exception is "+e);
        }
    }
}

What is datadriven framework in selenium ?

 

Datadriven framework and keyword driven framework are most popular framework in selenium automation world

many times there are requirement to do regression testing on regular basis. It will be hard if plan is to do one thing everyday for next 6 month.  Here is  automation engineer needs to create datadriven framework in selenium automation. It will allow to run same test on different data and configuration environment. for ex. You have a facebook login test and It will enter different 10 combinations for username and password now it will not  professional to write 10 step differently or do manually testing every time if you hard code that data in selenium java code then it is not a good way to deal this type of condition.

Here is huge benefits in datadriven framework  is you can store all the data in datasource like excelsheet and  let your java code read each row and run your test with each combination of username and password then it is called datadriven framework.

It is called datadriven framework because your data is in an excel sheet and you are driving your data in selenium test.

First read This Post to learn how to grab excel values in selenium test.

To understand this just see below code :-

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Datadriven_Framework
{
    @Test
    public void test()
    {
        Excel_File_Reader excel_file_reader = new Excel_File_Reader("path to your .xlsx file");    
        
        String username , password;
        
        // we are starting from 2nd row as we know that in first row we have column names.
        for(int i=2 ; i<=excel_file_reader.getRowCount("your sheet name") ; i++)
        {
            username = excel_file_reader.getCellData("your sheet name", "Username", i);
            password = excel_file_reader.getCellData("your sheet name", "Password", i);
            
            WebDriver wd = new FirefoxDriver();
            
            wd.get("http://facebook.com");
            
            WebElement username_txtbox = wd.findElement(By.xpath("//*[@id='email']"));
            username_txtbox.sendKeys(username);
            
            WebElement password_txtbox = wd.findElement(By.xpath("//*[@id='pass']"));
            password_txtbox.sendKeys(password);
            
            WebElement login_btn = wd.findElement(By.xpath("//*[@id='u_0_n']"));
            login_btn.click();
            
            wd.close();
        }
        
    }
}

As you will see all the information will come from excelsheet.

What is keyword driven framework in selenium ?

Keyword driven framework Selenium Automation

What ever actions you want to take on web element are store in an excel file. Suppose you want to click on web element then just write a method for it . So next time when you will supply parameters named in xpath in click() function. It will click on supplied web element. It will  click on all web elements you just need to write code once in a method as shown in below code :

public void click(String xpath)
{
    // wd is object of WebDriver
    WebElement login_btn = wd.findElement(By.xpath(xpath));
    login_btn.click();
}

Here we have passed xpath as parameter in method so this method is dynamic.

See here we have also method to open browser and write some text in text box. So our code is like write once and use it anytime using these methods.

See this is just overview of keyword driven framework in Selenium. In future post you will learn how to use keyword driven framework with excel sheet in Selenium Automation in brief.

You will store all the web element in the excel sheet and excess that web element and perform action on it. All web element will store as xpath or by Id whatever it is decide between QA and Development team. xpath will take some more time in IE or in regular term but by id will work fast.

 

How to find xpath when property don’t have ID for selenium automation testing?

There are many situation will come when a web element has not html property value like  id attribute. So you may question that how  to find xpath for that web element ?

For ex just look at below html code :-

<html>

<head>

<title>Xpath Demo</title>

</head>
 
<body> 
 
<div> 
<div> 
<a href="http://google.com">Click Here</a> 
</div> 
</div> 
</body> 
</html>

Now for instance we want to find xpath for hyper link named Clcik Here. So to create xpath for this hyperlink just follow below steps :-

1) Root element is html so our xpath starts with html.
2) Now after that hyper link is under body tag so add it and then our xpath will be html/body.
3) Now we have two div tags and then our hyper link. So we add first div as div[1] to our xpath and it will become html/body/div[1].
4) Now we will add second div and xpath will become html/body/div[1]/div.
5) Now at last our hyper link means a tag and our final xpath will become html/body/div[1]/div/a.

So in this way you can create xpath for a web element which does not have id attribute.

Open Safari web browser window and navigate it to a URL using Selenium Java on Windows OS.

Step – 1 :-

To write selenium code for this task you need two jar files and these are

1) selenium-api-2.43.1.jar and

2) junit-4.8.1.jar.

There are two options to get these jar files and these are given below :-

1) In your maven project in eclipse you have pom.xml. So open it and inside project tag paste below code :-

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.43.1</version>
</dependency>
 
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

2) First download all java jars needed from here -> Selenium Jars

Now in eclipse in package explorer right click on your maven project project -> properties -> Java build path -> Libraries -> Add external jars and then add all external jars to your project that you have downloaded from above URL.

Step – 2 :-

Now write below code to open Safari browser and navigate to URL :-

WebDriver wd=new SafariDriver();

wd.get("http://seleniumscript.com");
        
wd.close();

For above code you need to import below :-

org.openqa.selenium.WebDriver
org.openqa.selenium.safari.SafariDriver

The complete code is below and you can download source code from Attachments at the end of page :

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.safari.SafariDriver;

public class SafariDriver_Demo {

    @Test
    public void test()
    {
        WebDriver wd = new SafariDriver();
        wd.get("http://seleniumscript.com");
        
        wd.close();
    }
    
}

Open Internet Explorer web browser window and navigate it to a URL using Selenium Java on Windows OS.

Step – 1 :-

Now to write selenium code for this task you need two jar files and these are –

1) selenium-api-2.43.1.jar and

2) junit-4.8.1.jar.

There are two options to get these jar files as described below :-

1) In your maven project in eclipse you have pom.xml. So open it and inside project tag paste below code :-

<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.43.1</version>
</dependency>
 
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

2) First download all java jars needed from here -> Selenium Jars

Now in eclipse in package explorer right click on your maven project project -> properties -> java build path -> Libraries -> Add external jars and then add all external jars to your project that you have downloaded from above URL.

Step – 2 :-

Download IEDriverServer from here – IEServerDriver

Extract it to a specific location and you will need to give path to IEDriverServer.exe file.

Step – 3 :-

Now write below code to open IE browser and navigate to URL :-

System.setProperty("webdriver.ie.driver", “Path to your IEDriverServer.exe"); 
WebDriver wd=new InternetExplorerDriver(); 

wd.get("http://seleniumscript.com");
        
wd.close();

For above code you need to import below :-

org.openqa.selenium.WebDriver
org.openqa.selenium.ie.InternetExplorerDriver

The complete code is below and you can download source code from Attachments at the end of page :

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class IEDriver_Demo {

    @Test
    public void test()
    {
        System.setProperty("webdriver.ie.driver", "Path to your IEDriverServer.exe");
        WebDriver wd=new InternetExplorerDriver(); 
        
        wd.get("http://seleniumscript.com");
        
        wd.close();
    }
    
}