Automation Using Selenium Webdriver

Wednesday, 26 October 2016

Page Object Model Framework

Page Object Model
Selenium acts on web elements with the help of their properties such ID, name ,XPath, etc. Unlike QTP which has an inbuilt object repository (OR), Selenium has no inbuilt ORs.
Hence we need to build an OR which should also be maintainable and accessible on demand. Page Object Model (POM) is a popular design pattern to create an Object Repository in which each one of those web elements properties a recreated using a class file.

Advantages::

 POM is an implementation where test objects and functions are separated from each other, thereby keeping the code clean.
 The objects are kept independent of test scripts. An object can be accessed by one or more test scripts, hence POM helps us to create objects once and use them multiple times.
 Since objects are created once, it is easy to access as well as update a particular property of an object.POM Flow Diagram:

Objects are created for each one of the pages and methods are developed exclusively to access to those objects. Let us use http://calculator.net for understanding the same.
There are various calculators associated with it and each one of those objects in a particular page is created in a separate class file as static methods and they all are accessed through the 'tests' class file in which a static method would be accessing the objects.







Example
Let us understand it by implementing POM for percent calculator test.
Step 1 : Create a simple class (page_objects_perc_calc.java) file within apackage and create methods for each one of those object identifiers as shownbelow.

package PageObject;
import org.openqa.selenium.*;
public class page_objects_perc_calc
{
private static WebElement element = null;
// Math Calc Link
public static WebElement lnk_math_calc(WebDriver driver)
{
element =
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a"));
return element;
}

// Percentage Calc Link
public static WebElement lnk_percent_calc(WebDriver driver)
{
element =
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a"));
return element;
}
// Number 1 Text Box
public static WebElement txt_num_1(WebDriver driver)
{
element = driver.findElement(By.id("cpar1"));
return element;
}
// Number 2 Text Box
public static WebElement txt_num_2(WebDriver driver)
{
element = driver.findElement(By.id("cpar2"));
return element;
}
// Calculate Button
public static WebElement btn_calc(WebDriver driver)
{
element =
driver.findElement(By.xpath(".//*[@id='content']/table/tbody
/tr/td[2]/input"));
return element;
}
// Result
public static WebElement web_result(WebDriver driver)
            {
element =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b"));
return element;

                  }
             }
// Result
public static WebElement web_result(WebDriver driver)

{
element =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b"));
return element;
}
}


Step 2 : Create a class with main and import the package and create methodsfor each one of those object identifiers as shown below.

package PageObject;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class percent_calculator

{
private static WebDriver driver = null;
public static void main(String[] args)
{
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.calculator.net");
// Use page Object library now
page_objects_perc_calc.lnk_math_calc(driver).click();
page_objects_perc_calc.lnk_percent_calc(driver).click();
page_objects_perc_calc.txt_num_1(driver).clear();
page_objects_perc_calc.txt_num_1(driver).sendKeys("10");
page_objects_perc_calc.txt_num_2(driver).clear();
page_objects_perc_calc.txt_num_2(driver).sendKeys("50");
page_objects_perc_calc.btn_calc(driver).click();
String result =
page_objects_perc_calc.web_result(driver).getText();
if(result.equals("5"))
{
System.out.println(" The Result is Pass");
}
else
{
System.out.println(" The Result is Fail");
}
driver.close();
}
}
Output
The test is executed and the result is printed in the console. Given below is the snapshot of the same.







Comparing strings by their alphabetical order

class StringCompareExample {
    public static void main(String args[]){
        String s1 = "Project"; String s2 = "Sunject";
        verboseCompare(s1, s2);
        verboseCompare(s2, s1);
        verboseCompare(s1, s1);
    }

    public static void verboseCompare(String s1, String s2){
        System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");

        int comparisonResult = s1.compareTo(s2);
        System.out.println("The result of the comparison was " + comparisonResult);

        System.out.print("This means that \"" + s1 + "\" ");
        if(comparisonResult < 0){
            System.out.println("lexicographically precedes \"" + s2 + "\".");
        }else if(comparisonResult > 0){
            System.out.println("lexicographically follows \"" + s2 + "\".");
        }else{
            System.out.println("equals \"" + s2 + "\".");
        }
        System.out.println();
    }
}

Static keyword in java

Static keyword in java

The static keyword is used in java mainly for memory management. It is used with variables, methods, blocks and nested class. It is a keyword that are used for share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static.
No object needs to be created to use static variable or call static methods, just put the class name before the static variable or method to use them. Static method can not call non-static method.

In java language static keyword can be used for following

  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class

Static variable

If any variable we declared as static is known as static variable.
  • Static variable is used for fulfill the common requirement. For Example company name of employees,college name of students etc. Name of the college is common for all students.
  • The static variable allocate memory only once in class area at the time of class loading.

Advantage of static variable

Using static variable we make our program memory efficient (i.e it saves memory).

When and why we use static variable

Suppose we want to store record of all employee of any company, in this case employee id is unique for every employee but company name is common for all. When we create a static variable as a company name then only once memory is allocated otherwise it allocate a memory space each time for every employee.

Syntax for declare static variable:

public static variableName;

Syntax for declare static method:

public static  void methodName()
{
.......
.......
}
Syntax for access static methods and static variable

Syntax

className.variableName=10;
className.methodName();

Example

public static final double PI=3.1415;
public static void main(String args[])
{
......
......
}

Difference between static and final keyword

static keyword always fixed the memory that means that will be located only once in the program where as final keyword always fixed the value that means it makes variable values constant.
Note: As for as real time statement there concern every final variable should be declared the static but there is no compulsion that every static variable declared as final.

Example of static variable.

In the below example College_Name is always same, and it is declared as static.

Example

class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_Name); 
Student  s2=new  Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Name); 
}
}

Example

Output:
100
abcd
ITM
200
zyx
ITM
In the above example College_Name variable is commonly sharable by both S1 and S2 objects.

In the above image static data variable are store in method are and non static variable is store in java stack. Read more about this in JVM Architecture chapter

why main method is static ?

Because object is not required to call static method if main() is non-static method, then jvm create object first then call main() method due to that face the problem of extra memory allocation.

Read more about these things in separate

Java – Reverse String without using Reverse function

package JavaPrograms;
import java.util.*;
public class ReverseString {
public static void main(String args[])
{
String original, reverse ="";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + original.charAt(i);
System.out.println("Reverse of entered string is "+reverse);
}
}

Tuesday, 25 October 2016

Multi Select Action Drop Down

Keyboard Actions::

     Given below are the methods to perform keyboard actions:
 sendKeys - Sends keys to the keyboard representation in the browser.
     Special keys that are not text, represented as Keys are recognized both aspart of sequences of              characters, or individually.
 pressKey - Press a key on the keyboard that is NOT text. The keys suchas function keys "F1", "F2", "Tab", "Control", etc. If keyToPress is asequence of characters, different driverimplementations      may choose tothrow an exception or to read only the first character in the sequence.
 releaseKey - Release a key on the keyboard after executing the keypressevent. It usually holds        good for non-text characters.Here are the syntax to call keyboard functions using Selenium WebDriver.

void sendKeys(java.lang.CharSequence keysToSend)
void pressKey(java.lang.CharSequence keyToPress)
void releaseKey(java.lang.CharSequence keyToRelease)

Mouse Actions
Listed below are some of the key mouse actions that one would come across inmost of the applications:

 Click - Performs a Click. We can also perform a click based oncoordinates.
 contextClick - Performs a context click/right-click on an element orbased on the coordinates.
 doubleClick - Performs a double-click on the webelement or based on thecoordinates. If left empty,      it performs double-click on the current location.
 mouseDown - Performs a mouse-down action on an element or based oncoordinates.
 mouseMove - Performs a mouse-move action on an element or based oncoordinates.
 mouseUp - Releases the mouse usually followed by mouse-down andacts based on coordinates.

Here are the syntax to call mouse actions using Selenium WebDriver:
void click(WebElement onElement)
void contextClick(WebElement onElement)
void doubleClick(WebElement onElement)
void mouseDown(WebElement onElement)
void mouseUp(WebElement onElement)
void mouseMove(WebElement toElement)
void mouseMove(WebElement toElement, long xOffset, long yOffset)

Multi Select Action
Sometimes we would be in a situation to select two or more items in a list box ortext area. To understand the same, we would demonstrate multiple selectionfrom the list using
'http://demos.devexpress.com/aspxeditorsdemos/ListEditors/MultiSelect.aspx'.
Example
Let us say, we want to select 3 items from this list as shown below:




Let us see how to code for this functionality:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;
public class webdriverdemo
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().to("http://demos.devexpress.com
/aspxeditorsdemos/ListEditors/MultiSelect.aspx");
//driver.manage().window().maximize();
driver.findElement(By.id("ContentHolder_lbSelectionMode_I")).click();
driver.findElement(By.id("ContentHolder_lbSelectionModeSelenium100_DDD_L_LBI1T0")).click();
Thread.sleep(5000);
// Perform Multiple Select
Actions builder = new Actions(driver);
WebElement select =
driver.findElement(By.id("ContentHolder_lbFeatures_LBT"));
List<WebElement> options = select.findElements(By.tagName("td"));
System.out.println(options.size());
Action multipleSelect = builder.keyDown(Keys.CONTROL)
.click(options.get(2))
.click(options.get(4))
.click(options.get(6))
.build();
multipleSelect.perform();
driver.close();
         }
}

Output
Upon executing the script, the items would be selected as displayed above andthe size of the list box would also be printed in the console.






Automation framework Architecture and how to build a simple framework in Real Time

In this post we will design our automation testing framework (which will be called as SPOMFramework). The design will look like the one shown



FRAMEWORK ARCHITECTURE


Well, automation framework is a way to organize your code in much meaningful manner, so that any person who is luckily working with you should understand what each file (Code file can be either a vbscript file) has.
Automation framework are different types based on the above organizing of your code, it can be organized based upon your data, so that any person who has the better idea to handle the data files such as excel sheet will even have the handle to control the code !!!, well we call these types of frameworks as data driven frameworks.
Similarly there are some frameworks which can be fully written with keywords of functions such as Login, ClickButton, SearchList etc to enable automation engineers to work within framework much easily without ambiguity of same function or code and use the keywords within a framework for performing some operations, we call these type of framework as Keyword driven framework.
The combination of both of the above is called as Hybrid framework and there are some other frameworks which are named according to their usage such as Modular frameworks, structural framework etc.

Long story short, framework is a way to organize your complex code logics in more meaningful way to make our life easier. This can bring many advantages such as
Easy to understand the code
Easy to debug the code
Rapid development of code
Less error prone code
Automation frameworks are developed during the initial stage of any automation to begin, but as we know initial phase of automation will not have all the features which we are going to put in to the framework to make it more great, hence we will start with baby steps of what is called as
Folder structures, they are more of where we are going to place each and every codes within the folder. The folders in the folders structure are given more meaningful names such as “Utilities” folder, “Core” folder, “Test Data” folder etc.
Now once we have the folder structures in place, we can place the code files within those folders.
The folder structures are common for any frameworks or any automation testing tools which we will use. Well, the next big thing is “Reusability” of any code we write, the code must be written in such a way that it can be reused. The code written once should be written with intention in mind that the code can be reused by the team without many any or no changes in the code.
Similarly the code should also be “Generic” means the code should be compatible with more than one application. Since you are investing a lot of time in your framework design and development, tomorrow your company can come up with a new plan and can ask you automate application B while you have already in the process of automating application A. If you have written your framework more specific to Application A, then you will end up changing all your codes for Application B, hence try to avoid writing code more specific to a particular application. Well, there are cases where you can write very specifically for a particular application, in those cases, try to isolate the application specific stuffs in your framework and make it more visible, so that anybody working in framework can understand that its specific to application and not common to the whole framework.
Code written in automation must have clear comments in it, the comments should include the description of the code which can include the actual functionality of the code, if it has a return type then that too has to be specified, which is more normal as any programmers does, since automation test engineers are no different from a programmers, to me they are more than a programmers and a test engineer.
Wells what’s next, a basic structure of how your framework should look like, as every framework or design has its own structure, which can best understood by pictorial representation, I am also going to present you all via a pictorial representation of the framework structure as shown below.
As you could see in the diagram, the framework has got just 3 layers, but you can increase the layers of abstraction in such a way that it can have more than 3 layers to 10 layers. But it’s all depends upon your need and complexity of your automation framework.

The theory of framework layering is this, “The more you create the layers of abstraction, the more efficient your framework will be”.


Well this is the just an introduction about framework and I hope you got the basic idea of what a framework is all about.
What is a TEST Automation Framework?
A TEST Automation Framework is a set of guidelines like coding standards, test-data handling,object repository treatment etc., which when followed during automation scripting produce beneficial outcomes like increase code re-usability, higher portability, reduced script maintenance cost etc. 
Importantly these are just guidelines and not rules; they are not mandatory and you can still scriptwithout following the guidelines. But we will miss out on the advantages of having a Framework.
Ten Steps for Test Automation Framework Methodology:
• Identification of the Scope of Testing: Company oriented, Product oriented, Project Oriented.
• Identification of the Needs of Testing: Identify Types of testing e.g. FT, Web Services etc.
  and application / modules to be tested.
• Identification of the Requirements of Testing: Find out the nature of requirements, 
  identify type of actions for each requirement & identify high priority requirements.
• Evaluation of the Test Automation Tool: Evaluation checklist, Identify the candidate tools available 
  in the market, Sample run, rate & select the tools, Implementation & Training
• Identification of the Actions to be automated: Actions, Validations & requirements supported by the Tool
• Design of the Test Automation Framework: Framework guidelines, validations, Actions Involved, Systems involved, Tool Extensibility Support, Customs messages & UML Documentation.
• Design of the Input Data Bank: Types of Input file. Input files – Categorization &    Design of file prototypes.
• Development of the Automation Framework: Development of script based upon      framework design, 
  Driver scripts, Worker Scripts, Record / Playback, Screen / Window / Transaction, Action / Keyword & Data Driven.
• Population of Input Data Bank: Different Types of data Input, Populate data from different data sources, Manual input of data and Parent – Child data hierarchy.
• Configuration of the Schedulers: Identify scheduler requirements & configure the   schedulers.

Final keyword in java

Final keyword in java

It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is used at variable level, method level and class level. In java language final keyword can be used in following way.
  • Final at variable level
  • Final at method level
  • Final at class level


Final at variable level

Final keyword is used to make a variable as a constant. This is similar to const in other language. A variable declared with the final keyword cannot be modified by the program after initialization. This is useful to universal constants, such as "PI".

Final Keyword in java Example

public class Circle
{
public  static final double PI=3.14159;

public static void main(String[] args) 
{
System.out.println(PI);
}
}

Final at method level

It makes a method final, meaning that sub classes can not override this method. The compiler checks and gives an error if you try to override the method.
When we want to restrict overriding, then make a method as a final.

Example

public class A
{
public void fun1()
{
.......
}
public final void fun2()
{
.......
}

}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
 // it gives an error because we can not override final method
}
}

Example of final keyword at method level

Example

class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");  
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");  
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}  
} 

Output

It gives an error

Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes. When we want to restrict inheritance then make class as a final.

Example

public final class A
{
......
......
}
public class B extends  A
{
// it gives an error, because we can not inherit final class
}

Example of final keyword at class level

Example

final class Employee
{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");  
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}  
} 

Output

Output:
It gives an error