Automation Using Selenium Webdriver

Monday, 31 October 2016

Super keyword in java

Super keyword in java

Super keyword in java is a reference variable that is used to refer parent class object. Super is an implicit keyword create by JVM and supply each and every java program for performing important role in three places.
  • At variable level
  • At method level
  • At constructor level

Need of super keyword:

Whenever the derived class is inherits the base class features, there is a possibility that base class features are similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features and derived class features must be preceded by super keyword.

Syntax

 
super.baseclass features.

Super at variable level:

Whenever the derived class inherit base class data members there is a possibility that base class data member are similar to derived class data member and JVM gets an ambiguity.
In order to differentiate between the data member of base class and derived class, in the context of derived class the base class data members must be preceded by super keyword.

Syntax

 
super.baseclass datamember name
if we are not writing super keyword before the base class data member name than it will be referred as current class data member name and base class data member are hidden in the context of derived class.

Program without using super keyword

Example

class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+salary);//print current class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}

Output

 
Salary: 20000.0
In the above program in Employee and HR class salary is common properties of both class the instance of current or derived class is referred by instance by default but here we want to refer base class instance variable that is why we use super keyword to distinguish between parent or base class instance variable and current or derived class instance variable.

Program using super keyword al variable level

Example

class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}

Output

 
Salary: 10000.0

Super at method level

The super keyword can also be used to invoke or call parent class method. It should be use in case of method overriding. In other word super keyword use when base class method name and derived class method name have same name.

Example of super keyword at method level

Example

class Student
{  
void message()
{
System.out.println("Good Morning Sir");
}
}  
  
class Faculty extends Student
{  
void message()
{
System.out.println("Good Morning Students");
}
  
void display()
{  
message();//will invoke or call current class message() method  
super.message();//will invoke or call parent class message() method  
}  
  
public static void main(String args[])
{  
Student s=new Student();  
s.display();  
}
}

Output

 
Good Morning Students
Good Morning Sir
In the above example Student and Faculty both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority of local is high.
In case there is no method in subclass as parent, there is no need to use super. In the example given below message() method is invoked from Student class but Student class does not have message() method, so you can directly call message() method.

Program where super is not required

Example

class Student
{  
void message()
{
System.out.println("Good Morning Sir");
}
}  
  
class Faculty extends Student
{  

void display()
{  
message();//will invoke or call parent class message() method  
}
 
public static void main(String args[])
{  
Student s=new Student();  
s.display();  
}
}

Output

 
Good Morning Sir

Super at constructor level

The super keyword can also be used to invoke or call the parent class constructor. Constructor are calling from bottom to top and executing from top to bottom.
To establish the connection between base class constructor and derived class constructors JVM provides two implicit methods they are:
  • Super()
  • Super(...)

Super()

Super() It is used for calling super class default constructor from the context of derived class constructors.

Super keyword used to call base class constructor

Syntax

class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor  
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}

Output

 
Employee class Constructor
HR class Constructor
Note: super() is added in each class constructor automatically by compiler.

In constructor, default constructor is provided by compiler automatically but it also adds super()before the first statement of constructor.If you are creating your own constructor and you do not have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.

Super(...)

Super(...) It is used for calling super class parameterize constructor from the context of derived class constructor.

Important rules

Whenever we are using either super() or super(...) in the derived class constructors the superalways must be as a first executable statement in the body of derived class constructor otherwise we get a compile time error.
The following diagram use possibilities of using super() and super(........)

Rule 1 and Rule 3

Whenever the derived class constructor want to call default constructor of base class, in the context of derived class constructors we write super(). Which is optional to write because every base class constructor contains single form of default constructor?

Rule 2 and Rule 4

Whenever the derived class constructor wants to call parameterized constructor of base class in the context of derived class constructor we must write super(...). which is mandatory to write because a base class may contain multiple forms of parameterized constructors.

How to use String operations like as compare, replace, search and split string etc in Selenium Webdriver

How to use String operations like as compare, replace, search and split string etc in Selenium Webdriver
Common programming tasks like as compares the two given strings, searches the sequence of characters in this string, eliminates leading and trailing spaces, length of the string, a string replacing all the old char or CharSequence to new char or CharSequence, converts all characters of the string into lower to upper, upper to lower case letter etc and in Java has special String class that provides several methods to handle those type of operation. We can use String methods in selenium webdriver to operate these type tasks. This tutorial I will see how to use these String methods in selenium webdriver.


Method name: trim
Syntax : public String trim()
Purpose : Return string with omitted leading and trailing spaces

Method name: contains
Syntax : public boolean contains(CharSequence sequence)
Purpose : searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false.

Method name: format
Syntax : public static String format(String format, Object... args) )
Purpose : returns the formatted string by given locale, format and arguments.

Method name: startsWith
Syntax : public boolean startsWith(String Sequence_of_character)
Purpose : checks if this string starts with given Sequence of character. It returns true if this string starts with given Sequence of character else returns false.

Method name: endsWith
Syntax : public boolean endsWith(String Sequence_of_character)
Purpose : checks if this string ends with given Sequence of character. It returns true if this string ends with given Sequence of character else returns false.

Method name: equals and equalsIgnoreCase
Syntax : public boolean equals(Object anotherObject) or public boolean equalsIgnoreCase(Object anotherObject
Purpose : compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. equals method is case sensitive and equalsIgnoreCase is not case sensitive.

Method name: isEmpty
Syntax : public boolean isEmpty()
Purpose : checks if this string is empty. It returns true, if length of string is 0 otherwise false.

Method name: length or size
Syntax : public int length() or public int size()
Purpose : length of the string. It returns count of total number of characters.

Method name: replace
Syntax : public String replace(char oldChar, char newChar)
Purpose : returns a string replacing all the old char or CharSequence to new char or CharSequence.

Method name: split
Syntax : public String split(String regex)
Purpose : splits this string against given regular expression and returns a char array

Method name: toLowerCase
Syntax : public String toLowerCase()
Purpose : returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter.

Method name: toUpperCase
Syntax : public String toUpperCase()
Purpose : returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letter.

Demo Java Source Code
public class Stringmethodshandler {
   public static void main(String[] args) {
     String str_normal, str_equals, stra[];
     double formatnumer = 125.58655;
     str_normal = " Welcome to Java Demo Program ";
     str_equals = "Selenium Webdriver";
     // trim method example
     System.out.println("Befor Trim =: " + str_normal);
     System.out.println("After Trim =: " + str_normal.trim());
     // contains method example
     if (str_normal.contains("Demo")) {
       System.out.println("contains method pass");
     } else {
       System.out.println("contains method fail");
     }
     // startsWith method example
     if (str_normal.trim().startsWith("Welc")) {
       System.out.println("startsWith method pass");
     } else {
       System.out.println("startsWith method fail");
     }
     // endsWith method example
     if (str_normal.trim().endsWith("ogram")) {
       System.out.println("endsWith method pass");
     } else {
       System.out.println("endsWith method fail");
     }
     // isEmpty method example
     if (str_normal.isEmpty()) {
       System.out.println("isEmpty method pass");
     } else {
       System.out.println("isEmpty method fail");
     }
     // equals method example
     if (str_equals.equals("Selenium webdriver")) {
       System.out.println("equals method pass");
     } else {
       System.out.println("equals method fail");
     }
     // equalsIgnoreCase method example
     if (str_equals.equalsIgnoreCase("Selenium webdriver")) {
       System.out.println("equalsIgnoreCase method pass");
     } else {
       System.out.println("equalsIgnoreCase method fail");
     }
     // length method example    
     System.out.println("String length =: " + str_normal.length());
     // replace method example
     System.out.println("String replaced =: " + str_normal.trim().replace("Demo", "Example"));
     // format method example
     System.out.println("Format method examplet =: " + String.format("%.2f", formatnumer));
     // toLowerCase method example
     System.out.println("toLowerCase method example =: " + str_equals.toLowerCase());
     // toUpperCase method example
     System.out.println("toUpperCase method example =: " + str_equals.toUpperCase());
     // split method example
     System.out.println("============================================================");
     stra = str_normal.trim().split(" ");
     for (int i = 0; i < stra.length; i++) {
       System.out.println("splited string =: " + i + " " + stra[i]);
     }
   }
 }
Output
 Befor Trim =:  Welcome to Java Demo Program
 After Trim =: Welcome to Java Demo Program
 contains method pass
 startsWith method pass
 endsWith method pass
 isEmpty method fail
 equals method fail
 equalsIgnoreCase method pass
 String length =: 30
 String replaced =: Welcome to Java Example Program
 Format method examplet =: 125.59
 toLowerCase method example =: selenium webdriver
 toUpperCase method example =: SELENIUM WEBDRIVER
 ============================================================
 splited string =: 0 Welcome
 splited string =: 1 to
 splited string =: 2 Java
 splited string =: 3 Demo
 splited string =: 4 Program
Selenium Webdriver Demo Source Code
 import java.util.concurrent.TimeUnit;
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.firefox.FirefoxDriver;
 import org.openqa.selenium.support.ui.Select;
 public class SeleStringmethodshandler {
   public static void main(String[] args) throws InterruptedException {
     String selected_country_name, link_signup, strspilt[];
     // create objects and variables instantiation  
     WebDriver driver = new FirefoxDriver();
     // maximize the browser window  
     driver.manage().window().maximize();
     // launch the firefox browser and open the application url  
     driver.get("http://www.gmail.com/");
     //Set timeout  
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     // trim, equalsIgnoreCase method example
     Select countres = new Select(driver.findElement(By.id("lang-chooser")));
     selected_country_name = countres.getFirstSelectedOption().getText();
     System.out.println("Selected country name =: " + selected_country_name);
     if (!(selected_country_name.trim().equalsIgnoreCase("English (United States)"))) {
       countres.selectByValue("en");
     }
     // size method example
     for (int i = 0; i < countres.getOptions().size(); i++) {
       System.out.println("Country name =: " + i + " " + countres.getOptions().get(i).getText().trim());
     }
     // contains method example
     if (driver.getPageSource().contains("Gmail")) {
       System.out.println("Gmail is contain in www.gmail.com");
     } else {
       System.out.println("Gmail is not contain in www.gmail.com");
     }
     link_signup = driver.findElement(By.id("link-signup")).getText().trim();
     // startsWith method example
     if (link_signup.startsWith("Create")) {
       System.out.println("startsWith method pass");
     }
     // endsWith method example
     if (link_signup.endsWith("account")) {
       System.out.println("endsWith method pass");
     }
     // isEmpty method example
     if (!(link_signup.isEmpty())) {
       System.out.println("isEmpty method pass");
     }
     // equals method example
     if (link_signup.equals("Create account")) {
       System.out.println("equals method pass");
     }
     // toUpperCase method example
     System.out.println("toUpperCase method example =: " + link_signup.toUpperCase());
     // toLowerCase method example
     System.out.println("toLowerCase method example =: " + link_signup.toLowerCase());
     // split method example
     strspilt = link_signup.split(" ");
     for (int i = 0; i < strspilt.length; i++) {
       System.out.println(strspilt[i]);
     }
     // quit Firefox browser  
     driver.quit();
   }
 }


How to get hidden webelements text in Selenium Webdriver using Java

How to get hidden webelements text in Selenium Webdriver using Java
import java.util.List;
 import java.util.concurrent.TimeUnit;
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.firefox.FirefoxDriver;
 public class HiddenElementstext {
   public static void main(String[] args) throws InterruptedException {
     // create objects and variables instantiation    
     WebDriver driver = new FirefoxDriver();
     // maximize the browser window    
     driver.manage().window().maximize();
     // launch the firefox browser and open the application url
     driver.get("www.yahoo.com");
     //Set timeout    
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     //Get input tag and store in List variable name is number_of_hiddenElements
     List<WebElement> number_of_hiddenElements = driver.findElements(By.tagName("input"));
     //Print total number of Input tag
     System.out.println(number_of_hiddenElements.size());
     for (int i = 0; i < number_of_hiddenElements.size(); i++) {
       // Print all hidden elements text
       if (number_of_hiddenElements.get(i).getAttribute("type").trim().equalsIgnoreCase("hidden")) {
         //Check empty text
         if (!(number_of_hiddenElements.get(i).getAttribute("value").trim().isEmpty())) {
           //Print hidden Element texts
           System.out.println("Hidden Element text = " + i + " " + number_of_hiddenElements.get(i).getAttribute("value").trim());
         }
       }
     }
     // quit Firefox browser
     driver.quit();
   }
 }  

General Framework Structure in Selenium

Test Automation Frameworks
What is Framework?

A Test automation framework is an integrated system that can have the rules, standards and guidelines of automation of a specific application.

This system integrates the generic libraries, test data sources, object details, configuration modules, reporting and logs.


General Framework Structure:

Advantages:
1) Robust, flexible and extensible and support test automation on diverse sets of web applications across domains.
2) User-friendly interface for creation and execution of test suites.
3) Re-usability of code.
4) Increases test coverage to enhance the quality and reliability of the end product.
5) Easy maintenance.
6)Automated HTML report generation and emailing of the same to all stake holders

Types of Test Automation Frameworks
Data Driven Testing Framework
Keyword Driven Testing Framework
Hybrid Testing Framework
Page Object Model
1)Page Object Model

Now a days, Page Object Model become very popular test automation framework in Selenium, where web application pages are represented as classes, and the all the web elements on the page are defined as variables on the class. All possible user interactions can be implemented as methods on the class.

Please find the link for Page Object Model in Selenium.

2) Data Driven Framework

If you observe several times while testing an application, it may be required to test the same functionality multiple times with the different set of input data, In that situation, if you hard-coded the test data to automation test scripts will not useful for reusability. So instead of hard-coded test data you have to store it in external files like excel, xml, properties file, database, csv.
So in order to test the application, you have to connect with external files and get the test data from them.

How to work with Firefox browser using Selenium 3.0 beta 1

How to work with Firefox browser using Selenium 3.0 beta 1

Recently selenium has launched Selenium 3.0 beta 1 jar.In this post I will show you How to work with Firefox browser using Selenium 3.0 beta 1 jar.

Please follow the below steps:
Step:1
Just like the other drivers available to Selenium from other browser vendors, Mozilla has released now an executable that will run alongside the browser

In order to work with Firefox browser using Selenium 3 beta 1 jar, you need to use separate a driver which will interact with Firefox browser called as "Geckodriver".

Please find below link for downloading latest version of geckodriver.

https://github.com/mozilla/geckodriver/releases/download/v0.9.0/geckodriver-v0.9.0-win64.zip

Step:2
System.setProperty("webdriver.gecko.driver", "path/to/geckodriver.exe");

Step:3
driver = new FirefoxDriver();

Note: Still if you are using old versions of selenium jars(selenium 2) then you can skip first two steps.

Sample Code:
public class SampleTest {

 public WebDriver driver;

 @Test
 public void setup(){

  System.setProperty("webdriver.gecko.driver", "E:/geckodriver.exe");
  driver = new FirefoxDriver();
  driver.manage().window().maximize();
  driver.get("http://www.facebook.com/");

  }

}