How to create Object Repository in Selenium

Unlike QTP/UFT, Selenium does not offer the default implementation for  object repository. In QTP things are really straightforward, just object spy the controls and add to object repository, and further with the blessings of intellisense feature in its IDE, utilize them easily in writing scripts.

But how we can achieve the same in selenium??..
It can be done by using Properties file feature of Java. Lets begin with some basic explanation.

What is Object Repository?

Object Repository is a centralized location where we can store objects information, it acts as interface between Test script and application in order to identify the objects during the execution.

We always recommend using external file for object repository rather than hard coding the objects and its properties directly into our code. Why this??? As it reduces the maintenance  effort and provides positive ROI, for example say any of the object properties change within our application under test, we can easily change it in external object repository file, rather than searching and doing updates  for that object individually in the code.

Principle:
A basic object repository can be implemented as a collection of key-value pairs, with the key being a logical name identifying the object and the value containing unique objects properties used to identify the object on a screen. For this, we will use a .properties file in Java which is a basic collection of key-value pairs.

Creating Properties File in Eclipse:-

Step1:-
Right click on the Package in the solution Explorer of Eclipse-> New ->Other

Creating Properties file in Eclipse
Adding New File in Eclipse

Or 
Right click on the Package in the solution Explorer of Eclipse-> New ->File (In this case Step-2 below is not required)

Create new file in eclipse
New ->File in Eclipse


Step2:
General ->File ->Click Next

New file wizard in Eclipse
New Wizard in Eclipse

Step3:-
Give name to the file with .properties extension (Say OR_Gmail_Login.properties) ->Click Finish

Properties file in Java Eclipse
Naming Properties File in Eclipse



Note:- 
We generally create each properties file for every single page and capture all the UI elements present on the page and use it as per the needs.


Adding Key/value Pairs in Properties File:-

Before adding our objects into object repository, let’s outline a simple scenario that we will be automating in Selenium:-

1. Launch Gmail login page.
2. Fill the Username & Password fields and click on Submit button

After creating our empty properties file, now we need to add our elements, in the form of key and Value pairs.
For Example:-

Gmail.LoginPage.txtPassword -> Key
Passwd->Value

Note: – In Value property we have taken the Locator and its value, which will be used to identify our control. As password field, is getting uniquely identified by ID field so we have taken that value.

Properties file with objects in Selenium
Properties File in Java



Code:-

package OR;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
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 PropertiesFile {
public static void main(String[] args) {
//Creating the File Object
File file = new File("D:\Automation\Selenium\MyCode\FirstSeleniumCode\src\OR\OR_Gmail_Login.properties");
//Creating properties object
Properties prop = new Properties();
//Creating InputStream object to read data
FileInputStream objInput = null;
try {
objInput = new FileInputStream(file);
//Reading properties key/values in file
prop.load(objInput);
//Closing the InputStream
objInput.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());

} catch (IOException e) {
System.out.println(e.getMessage());
}
//Creating the driver instance
WebDriver driver = new FirefoxDriver();
//Adding wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Launching the GMAIL page
driver.get(prop.getProperty("Gmail.URL"));
//Entering the UserName
WebElement element = driver.findElement(By.id(prop.getProperty("Gmail.LoginPage.txtUserName")));
element.sendKeys("uftHelp@gmail.com");
//Entering the Password
element = driver.findElement(By.id(prop.getProperty("Gmail.LoginPage.txtPassword")));
element.sendKeys("uftHelp");
//Clicking the SignIn button
element = driver.findElement(By.id(prop.getProperty("Gmail.LoginPage.btnSignIn")));
element.click();
System.out.println("Test Scenario Completed!!");
//Destroying the driver object
//driver.close();

}
}

Working with Text Files in Selenium using Java

Today we are going to focus on learning to work with Text Files in Selenium
We have already dealt with Exceptions in Selenium now we will focus on how to open/write/read to a text file. Further we would utilize the learning in our real life example of reading all the links on page and write it into a text file using Selenium.

Don’t forgot to like our FB page to learn more.


Text files in Selenium
Learn working with Files


Important Tips for Reading a File:-

1.While working with files, we need to handle the Checked Exception in our code, otherwise our code will not compile.

2.FileReader class makes it possible to read the contents of a file as a stream of characters, thus we are using in our code to read characters from a text file.

FileReader fr = new FileReader(filePath)


3.BufferedReader class provides buffering to our FileReader. Rather than reading one character at a time from the file, we read a larger block at a time using BufferedReader.

FileReader fr = new FileReader(filePath)
BufferedReader txtReader = new BufferedReader(fr)

We can specify the buffer size in the above case we have used the default size(8192 chars).
Incase we want sized buffer our code will look like this:-

Int bufferSize = 1000
BufferedReader txtReader = new BufferedReader(fr, bufferSize)


4.ReadLine, method of BufferedReader Class, which reads a line of text. A line is considered to be terminated by any one of a line feed (‘n’), a carriage return (‘r’), or a carriage return followed immediately by a linefeed.

Code:-

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WorkingwithFiles {
public static void main(String[] args) {
//FilePath
String sFilePath = "D:\Automation\Selenium\TestFile.txt";
//Creating FileReader object
FileReader fr = null;
//Creating BufferedReader object
BufferedReader txtReader = null;
//Handling Exception using Try-Catch
try {
String sCurrentLine;
fr = new FileReader(sFilePath);
txtReader = new BufferedReader(fr);
//Reading file until file is null
while ((sCurrentLine = txtReader.readLine()) != null) {
System.out.println(sCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (txtReader != null)txtReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}

}
}

Important Tips for Writing into a File:-

1.FileWriter class makes it possible to write a file as a stream of characters, same like FileReader above.

FileWriter fw = new FileWriter(filepath)

2.Incase we want to control whether to append or overwrite into text file

Boolean append = True
FileWriter fw = new FileWriter(filepath, append)

By Default it is “False”, thus it will overwrite the existing data.

3.BufferedWriter class provides buffering to our Write. Rather than write one character at a time to the file, we write a larger block at a time. This is typically much faster, especially for disk access and larger data amounts

FileWriter fw = new FileWriter(path)
BufferedWriter bw = new BufferedWriter (fw)


We can control the size of bufferedwriter like we did in bufferedreader class

4.We used File objects to obtain information about a file or directory.File object is used to obtain information about a particular file or directory and is not used to read or write data, like length of a file

Code:-

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


public class WritingInFiles {
public static void main(String[] args) {
//Data to write
String sContent = "Lets try to write newline into File";
//FilePath
String sFilePath = "D:\Automation\Selenium\TestFile.txt";
try {
//Creating File object
File file = new File(sFilePath);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//Creating FileWriter object
//using file object we got the filePath
FileWriter fw = new FileWriter(file.getAbsoluteFile());
//Creating BufferedWriter object
BufferedWriter bw = new BufferedWriter(fw);
//Writing content into file
bw.write(sContent);
//Adding new line
bw.newLine();
bw.close();
System.out.println("Data is Successfully written");

} catch (IOException e) {
e.printStackTrace();
}
}

}

How to Catch Exceptions in Java?

We understood the basics of Exception in Java, now we will move towards handling these exceptions. We are aware of the fact that when error is detected, an exception is thrown. This means the normal code execution stops and the control are transferred to the catch clause for that exception of the first enclosing try block. The try block might be in the current function (the one that caused the error), or it might be in some function that called the current function (if the current function is not prepared to handle the exception, it is “passed up” the call chain).Furthermore in case no currently active function is prepared to catch the exception, an error message is printed and the execution stops.

Lets elaborate on what we said above.We can connect on FB for more learning!!

How to catch exceptions?

Try Catch in Java
Try-Catch


Using Try-Catch:-

Try Block:-This block is placed around the code that might generate an exception. Therefore try block is one that is used to wrap the exception prone code inside it,making our code protected.

Catch block:- This part have the declaration of the type of exception we are trying to catch. Here we can code for what action need to be taken on exception (Say publishing the error trace or giving error message to user)

Syntax:-

try {
//Our code 
} catch (ExceptionType name) {
name.printStackTrace();
}





Explanation:-
ExceptionType:- declares the type of exception that the handler can handle.


name:-The handler can refer to the exception with name, Java exceptions are objects, so the statements in a catch clause can refer to the thrown exception object using the specified name.

printStackTrace:- It helps us to find the exact error location and name of the method causing the error in our code. In Java execution, each program has the details of its invoking methods onto the execution stack, plus the classes and object names and the line number of the code line that is being executing. Whenever an exception is triggered printStackTrace() can be used to print the contents of the execution stack, and we can fetch the details.

Code:-

Division by Zero 

public class ExceptionHandling {

public static void main(String[] args) {
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("We are in the catch block");
}
}

}


Output:-

Divide by Zero Exception caught in Java
Arithmetic Exception

Explanation:-

We are dividing by zero and we are handling that exception using the catch block, in that block we are taking the output of “Stack” which is shown as ArthemeticException:/ by Zero and gives us the line where exception is thrown i.e 6 in our case.


Important Tips:- 

1) We can have multiple Catch blocks, by providing one or more catch blocks directly after the try block.

Syntax:-

try {

} catch (ExceptionType1 name1) {

} catch (ExceptionType2 name2) {

}


2) We can Catch More Than One Type of Exception with only One Exception Handler(Catch). We need to specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|)

Syntax:-

try {
} catch (IndexOutOfBoundsException | IOException e){

}


In this example, the catch parameter e is final(Constant value) and therefore we cannot assign any values to it within the catch block.

3) Arrange multiple, Catch blocks using narrow to broader approach.

For example:- 

catch (I/OException e) {
   //statements to handle this exception 
}
catch (FileNotFoundExcetption e) {
//statements to handle this exception
}


Here incase of some I/O exception (say while working with files) , first block of catch will always be executed irrespective even “FileNotFoundException” is thrown.Beacuse “I/OException” is superclass to “FileNotfoundException” which is the subclass, so our correct order should be:-

catch (FileNotFoundExcetption e) {
//statements to handle this exception
}
catch (I/OException e) {
//statements to handle this exception
}

4) Try-Catch block can also be followed by Finally Block(optional).

  • This block of code always executes, whether or not an exception has occurred.
  •  Only in some exceptional scenarios it might not execute like the thread executing the try or catch code is interrupted or killed, JVM exits while the try or catch code is being executed.
  • It is a good practice to use this block for code cleanup, to free the resources after the execution exits. 
  • The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered

Syntax:-

try
{
//Our code
}
catch(ExceptionType name)
{
}
finally
{
//I will always executes.
}

5) Try block cannot exist without Catch or Final blocks and vice versa.

6) We can create our own exceptions and utilize the throws and throw keyword to initiate that exception.

7) “Exception” class can handle any type of exception, so our handler will look like

Syntax:-
// Common exception handler

catch (Exception e) {
...
}


Note:-Always try to catch specific exceptions. Avoid catching System.Exception whenever possible.

8)Code that detects errors often does not know how to handle them.The best approach is to use exceptions.We catch them using Try-Catch and Exceptions are thrown using a throw statement.

But mostly it is recommend having exception handlers to be as specific as possible,firstly because  a handler must do is determine what type of exception occurred before it can decide on the best recovery strategy, secondly this is general handler and can make code more error-prone by catching and handling exceptions that we never wanted to capture and for which the handler was not intended

What can be done when calling a function that may throw an exception?

1. Catch and handle the exception there itself

Example :- 
Method A calls Method B, and we are catching the exception in Method B itself.

public class ExceptionHandling {
public static void main(String[] args){
//Calling MethodA
MethodA();
}
//MethodA
static void MethodA(){
//Call to MethodB
MethodB();
System.out.println("We are inside MethodA");

}
//MethodB
static void MethodB(){
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("We are in the catch block of MethodB");
}
}
}


Output:-

Catch Exception in Java
Catch Exception in the originating Method


2. Catch the exception, then re-throw it or throw another exception

Example :- 
Method A calls Method B, and we are catching the exception in Method B  and throwing another exception.

public class ExceptionHandlingThrow {
public static void main(String[] args){
//Calling MethodA
MethodA();
}
//MethodA
static void MethodA(){
//Handling the thrown Exception
try{
//Call to MethodB
MethodB();
}catch(ArithmeticException e){
System.out.println("We are inside MethodA it will catch Exception");
System.out.println(e.getMessage());
}
}
//MethodB
static void MethodB() throws ArithmeticException{
try {
int a = 1/0;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("We are in the catch block of MethodB and it will Throw Exception");
throw new ArithmeticException("Exception of Divide by Zero");
}
}
}





Output:-




Throw Exception in Java Example
Throw Exception to the calling Method




3. Ignore the exception (let it "pass up" the call chain).
Example :- 

Method A calls Method B, and we are throwing the exception in Method B and it is catched by Main method

public class ExceptionHandlinginMainMethod {
public static void main(String[] args){
//Calling MethodA
try{
MethodA();
}catch(Exception e){
System.out.println("We are inside Main Function");
e.printStackTrace();

}
}
//MethodA
static void MethodA(){
//Call to MethodB
MethodB();

}
//MethodB
static void MethodB() {
System.out.println("We are inside MethodB it will not catch Exception");
int a = 1/0;
}
}


Output:-

Main method handles Exception in java
Main method handles Exception


Difference between Throw and Throws

Note:- We have taken the code example to explain the difference of Throws and Throw from the above complete code(Point 2)

Throw v/s Throws in Java Selenium
Throw v/s Throws in Java



Why to use Exceptions?

It helps in error handling 🙂 , very simple and straightforward, but it also help us to give structure to our code by separating the “Error-Handed” code from the “Regular code”.

We can group same error types.

For example:-
IOException exception represents any type of error that can occur when performing I/O.On the other hand “FileNotFoundException ” is the subclass of this, which handles only missing file exception.So we can have specific handlers that can handle a very specific exception

catch (FileNotFoundException e) {
...
}

Or to catch all exception based on its group or general type by specifying any of the exception’s superclasses in the catch statement like I/O Exceptions

catch (IOException e) {
...
}

Exception handling in Java?

Exception handling plays a crucial part in mastering Selenium, and designing Frameworks, thus we thought of digging deeper into this topic.We have also discussed about ways of handling Exceptions.


Let’s begin with keynotes before starting with the detailed explanation:-

  • An exception is any event, which interrupts the normal flow of the program execution.
  • Throwable‘ class is the superclass (remember Object class is the superclass of all the Java classes) of all errors and exceptions in the Java language.
    Throwable is SuperClass of all Errors in Java
    SuperClass and SubClass in Java

  • Types of Exceptions ‘checked exceptions’ and ‘unchecked exceptions’. All RuntimeExceptions and Errors are unchecked exceptions. Rest of the exceptions are called checked exceptions.
  • Checked exceptions should be handled in the code to avoid compile time errors.
  • Exceptions can be handled by using ‘try-catch‘ block. Try block contains the code to be handled from exception, while catch block contains the remedy for the exception.
  • The finally block after a try … catch statement is executed regardless whether an exception is caught or not.
  • Incase a method doesn’t handle the exception, hence it is mandatory to specify the exception type in the method signature using ‘throws‘ clause.
  • We can explicitly throw an exception using ‘throw‘ clause.

Do like our Facebook page to learn more.

What is Exception?

An exception is a problem, which occurs during the execution of a program, and it results in interrupting the normal flow of the program’s implementation.

It can be in the form of invalid input data, type mismatch, File not found, and network failure and many more.

Flow of Exception:-

Error ->Exception object ->Caught

Error in the program, results in the creation of Exception object at runtime which contains information about the error, including its type and the state of the program when the error occurred. 

Now Java runtime attempts to find a block of code (Exception Handler) that can handle the exception in our program. It starts searching from the current method to calling methods in reverse and at last the main method. If an appropriate handler code is found then the exception is handled normally, otherwise program terminates.


Types of Exception:-

Exception Types in Java
 Exception Hierarchy 


Checked exception: – 
These exceptions are checked at compile time and it refers to the exceptional scenario that a well-written application should try to recover from.

It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. That is the reason it is known as checked Exception because these exceptions are checked at Compile time

For example, while working with external files, incase we try to compile the code without any exceptional handling,compilation error will be thrown and user is forced to handle that, before starting with the execution.So we need to add try-catch block or need to throw  IOException.
More examples NoSuchMethodException, ClassNotFoundException.

Unchecked Exception: – 
These are not checked at compile time, it means if our program is throwing an unchecked exception and even if we  didn’t handle/declare that exception, the program won’t give a compilation error. 

It consists of Error and Runtime Exceptions.

Error: –
It is type of exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. Typical Java programs should not catch Errors.

For example, say our code is able to open the file for reading but due to hardware or system failure, this operation is not successful. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem or it also might make sense for the program to print a stack trace and exit.

Runtime Exception: –
These are exceptional conditions that are internal to the application, and   represent problems that are the result of a programming, such as logic errors or improper use of an API.

For example, we are able to pass the filename to FileReader method but our logic passes a null object to the method, thus ‘NullPointerException’ will be thrown. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.

More examples, dividing by zero(ArithmeticException), attempting to access an array element through an index that does not exists(ArrayIndexOutOfBoundsException)

Note: – 
Runtime exceptions can occur anywhere in the application flow.Does this means we need to add runtime exceptions in every method declaration, where it can happen?.However it would reduce a program’s clarity. Furthermore, the compiler does not require that we catch or specify runtime exceptions (although we can).So we generally avoid handling Runtime Exception.

Now we are done with the basics of Exception and its types in Java, in our next post we would learn handling Java exceptions.

Learn Object Spy in UFT

Hello Friends!! My name is object spy. You can find me in my new avatar of hat and goggles in UFT. Today I am going to tell you about myself.

Object spy in UFT
My new look 
Introduction to Object Spy?

I am an inbuilt tool which comes bundled with UFT, I help automation testers with following capabilities:-


1. Highlight the object. (How to do highlight in Selenium)
2. Adding objects to Object repository.
3. Check the properties of object (also you copy that to clipboard).
4. Check what all the operations that can be performed on the object.
Object Spy UFT
Object Spy UFT
How to launch me?

1.       From menu bar icon

Launch object spy from menu bar
Launch from Menu Bar
2.       Tools -> Object Spy

Object Spy in Tools
Object Spy launch from Tools
3.       Resources -> Object  Repository Manager

Launch object spy object repository manager
Launch from object repository manager
4.       Resources -> Object Repository
Launch Object spy from local OR
Launch from local OR
Understand my UI?

Hand: – This is the point where you can start my interaction with the objects, just click it and move my hand over the required object and ill provide you the properties which is consumed by UFT in object identification. Moreover you can press CTRL key to hide my hand to perform normal operations of mouse.
Press CTRL key in object spy UFT
Working with hand icon in object spy
Highlight:
This feature of mine will be disabled until and unless no object is added to my UI.
Highlight button is disabled
Highlight is disabled 
Highlight button enabled in object spy
Highlight/add to OR/ Copy to clipboard are enabled one’s object is added
One’s the object is added ill help you highlight that particular object in the application (with a blink around that object.)

Note: – 
Incase I am not able to find the object due to nonexistent of object or properties are not unique, I’ll generate an error message like below.

Highlight failure message UFT
Error message for non exiting object in application 
Add object to object repository (OR):
Using this feature you can add the selected object to object repository.

Add objects to OR in object spy
Add objects to OR

Note:
  • Only the selected object from the hierarchy will be added to OR
  • One’s that object is added to OR, this button will become disabled and small bucket like symbol will appear next to the object.
  • Object will be added to local Object repository incase i am launched from Local object repository or from menu bar icon or from tools options. I will add object to shared OR only incase i am launched from object repository manager.


Adding object to OR from object spy
Object added to OR 

Copy to clipboard:-
Click on this button to copy all the object properties in ,name:=value pair combination. 
Copy to clipboard in object spy
Copy to clipboard in Object Spy

Paste them in any of the editor say notepad, to employ in automation.

Copy object properties in object spy
Copied object properties from object spy
Note:– 
This feature is important while working with descriptive programming(DP) in UFT, as you can utilize this properties in DP.

Keep me on Top while spying:-
You can keep me on the top of the application while hand button is active or make me invisible while object spy is active.

Keep object spy on top while spying
Keep object Spy in top of Application while spying 
Tips:
I am really powerful, as when I am active, you can’t perform any operation in UFT, so you need to close me before you can work on UFT or Object repository manager.

How to work with me:

Launch me -> click on hand -> hover over the object with which you want to work -> select it -> Try to highlight (to cross check that we have captured the correct object) -> add to OR / copy to clipboard/ check properties or operations that can be performed on object

Note:
  • Under properties: – we can select identification and native properties/operations.
  • Identification Properties are properties that UFT uses to identify objects in application, these come as name value pairs like “title: =HOME”.


Object Spy identification properties dialog box
Object spy Identification Properties

When to use Native properties/operations?

Sometimes my identification properties are not enough to fulfil many automation requirements. To deal with these problems you can leverage ‘Native Properties’ of the application under test.

Note:-
You can retrieve native properties value for an object using .object

Below example shows the native properties/methods of link object.
Native method of link in UFT
Working with Native properties and Methods

You can find the same native methods/properties for link in my UI.


Link native methods in UFT
Link Native methods

  • Native properties are properties as created by the creator of object, e.g. Microsoft is creator for IE explorer objects.
  • Identification properties are subset of native properties.
  • We can use .object to retrieve Native Properties, utilize native operations, and manipulate native properties.

Hope this crisp introduction about myself, help You know and understand my usage in UFT. Do share your comments or feedback below . Will be happy to hear from You. Bye bye J

How to implement Highlight in Selenium WebDriver?

Highlight is the most prominent feature used in Object Spy in UFT/QTP. But the question comes into our mind can we have the same facility in Selenium also?.

Answer is YES!!

Highlight selenium
I want to highlight object in selenium

Why we use Highlight?
Highlight plays crucial role in  debugging of  test script. One way to know steps being performed in browser is to highlight the web page elements.

How is it possible?

Core principle is to use “JavaScriptExecutor” to inject javascript into our application, which will change the CSS properties of the element at runtime and we can pinpoint(visible see) the element with changed set of properties.

Example:- We can simply change the  the backgroundColor/border of the specified element yellow.(Like we see on clicking Find button in Selenium IDE).

Note:-

In Selenium RC we had a dedicated command for the same.
Syntax:-

selenium.highlight(“element Locator”); element locator = id,css,xpath..

Code:-

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.border='2px groove green'", element);


                                                                  OR

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: Red; border: 2px dotted solid green;");
js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "");


Explanation:-

Don’t be afraid from the messy code, lets try to understand it ,
Arguments[0].style.border:– this script is injecting the CSS style tag into the element , and making its border settings with a 2px wide green line with groove look.
Element :- This is the element around which border will be drawn.

We can also try the following code also :-

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('test').style.border='2px groove green';");

Working Demo:-

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class HighLightMe {

public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
//Open Application
driver.navigate().to("http://www.uftHelp.com");
//Maximize the browser
driver.manage().window().maximize();
//Find the element to highlight
WebElement element = driver.findElement(By.xpath("//a[contains(text(),'Home')]"));
//Function call to Highlight the element
fnHighlightMe(driver,element);


}

public static void fnHighlightMe(WebDriver driver,WebElement element) throws InterruptedException{
//Creating JavaScriptExecuter Interface
JavascriptExecutor js = (JavascriptExecutor)driver;
for (int iCnt = 0; iCnt < 3; iCnt++) {
//Execute javascript
js.executeScript("arguments[0].style.border='4px groove green'", element);
Thread.sleep(1000);
js.executeScript("arguments[0].style.border=''", element);
}
}

}



Learn More

What is JavaScriptExecutor in Selenium?

What is JavaScriptExecutor?

JavaScriptExecutor is an interface which provides mechanism to execute Javascript through selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window. 

JavaScriptExecutor in Selenium
Lets inject Javascript into Browser using Selenium

Why we use it?

To enhance the capabilities of the existing scripts by performing javascript injection into our application under test.

In simple words  “Javascript can be executed within the browser with the help of JavaScript Executor.”

Package:-

import org.openqa.selenium.JavascriptExecutor;

Syntax:-

JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);



script – The JavaScript to execute
Arguments – The arguments to the script.(Optional)


Scenario’s

1.How to generate Alert Pop window in selenium?

Code:-

JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello world');");


2.How to click a button in Selenium WebDriver using JavaScript

Code:-

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);


3.How to refresh browser window using Javascript ?

Code:-

JavascriptExecutor js = (JavascriptExecutor)driver;
driver.executeScript("history.go(0)");

4.How to get innertext of the entire webpage in Selenium?

Code:-

JavascriptExecutor js = (JavascriptExecutor)driver;
string sText = js.executeScript("return document.documentElement.innerText;").toString();



5.How to get the Title of our webpage ?

Code:-

JavascriptExecutor js = (JavascriptExecutor)driver;
string sText = js.executeScript("return document.title;").toString();


6.How to perform Scroll on application using  Selenium

Code:-

  JavascriptExecutor js = (JavascriptExecutor)driver;
//Vertical scroll - down by 50 pixels
js.executeScript("window.scrollBy(0,50)");


Note:- for scrolling till the bottom of the page we can use the code like

js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

7.How to click on a SubMenu which is only visible on mouse hover on Menu?

Code:-

    JavascriptExecutor js = (JavascriptExecutor)driver;
//Hover on Automation Menu on the MenuBar
js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");

8.Implement Highlight in Selenium?

9.How to navigate to different page using Javascript?

Code:-

JavascriptExecutor js = (JavascriptExecutor)driver;
//Navigate to new Page
js.executeScript("window.location = 'https://www.facebook.com/uftHelp'");




Working Demo:-

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


public class JavaScriptExecuter {

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
//Launching the browser application
driver.get("http://www.uftHelp.com");
//Adding wait
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Maximize window
driver.manage().window().maximize();
//Creating the Javascriptexecutor interface object by Type casting
JavascriptExecutor js = (JavascriptExecutor)driver;
//Fetching the Domain Name
String sDomain = js.executeScript("return document.domain;").toString();
System.out.println("Domain = "+sDomain);
//Fetching the URL
String sURL = js.executeScript("return document.URL;").toString();
System.out.println("URL = "+sURL);
//Fetching the Title
String sTitle = js.executeScript("return document.title;").toString();
System.out.println("Title = "+sTitle);
//Vertical scroll - down by 200 pixels
js.executeScript("window.scrollBy(0,200)");
System.out.println("Successfully did the vertical scroll by 200px");

}

}


Working with Action Interface in Selenium

To perform Advanced User Interactions, like drag and drop, keyboard events; selenium came up with Action and Actions interface under a  comprehensive API, named as Advanced User Interaction which facilitate user actions to be performed on a application. Thus users can use this API to simulate usage of keyboard or mouse events.

Learn Action class in Selenium
Lets do some Action in Selenium



Example:-

  • To double-click a control we have DoubleClick(), method of Actions Class.
  • To Send keyboard actions, we have SendKeys() ,method.(Equivalent to WebElement.sendKey(…))
  • Clicking the mouse button that brings up the contextual menu.we can use “ContextClick()”, method.

Package:-

import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;

Syntax:-

 Actions oAction=new Actions(selenium);
oAction.contextClick(element).perform();

  

Methods of Action class selenium
Actions Class Methods



Explanation:-

We need to import above packages to access the action and actions class methods.Create the actions class object and access the range of available methods.

What about multiple mouse and keyboard actions?

In above case we simply performed one action on the element, incase we want to perform sequence of events on the same element, we can achieve same by using build method.

Code:-

   Actions oAction=new Actions(selenium);
Actions moreActions = oAction
.moveToElement(element)
.click()
.keyDown(element,Keys.SHIFT)
.sendKeys(element,"selenium");

Action enterInCaps= moreActions.build();
enterInCaps.perform();


Scenarios:-

1.How to right click and open the application in new window.

Code:-

        Actions oAction=new Actions(selenium);
oAction.contextClick(element).perform();
oAction.sendKeys("w").perform();




2.How to fetch tool tip of a control in Selenium .

Code:-

 Actions oAction=new Actions(selenium);
oAction.clickAndHold(element).perform();


3.How to send text in capital letters into a text-box?

Code:-

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;


public class ActionClass {

public static void main(String[] args) {
WebDriver selenium = new FirefoxDriver();
System.out.println("Launching Browser");
//Opening the URL
selenium.get("http://www.uftHelp.com");
//Implicit wait for the browser to launch
selenium.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Google Search Text-box
WebElement element =selenium.findElement(By.id("gsc-i-id1"));
//Creating action class object
Actions oAction=new Actions(selenium);
//Creating action collection to perform numerous methods on element
Actions moreActions = oAction
.moveToElement(element)
.click()
.keyDown(element,Keys.SHIFT) //for caps
.sendKeys(element,"selenium");

Action enterInCaps= moreActions.build();
enterInCaps.perform();
System.out.println("Text is entered in Captial letters");
//Closing the browser
//selenium.quit();
}

}


4.How we can drag and drop element in selenium?
  
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.interactions.Actions;


public class DragAndDrop {

public static void main(String[] args) {

WebDriver selenium = new FirefoxDriver();
System.out.println("Launching Browser");
//Opening the URL
selenium.get("http://jqueryui.com/resources/demos/droppable/default.html");
//Implicit wait for the browser to launch
selenium.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Identifying the elements to perform action
WebElement draggable = selenium.findElement(By.xpath("//*[@id='draggable']"));
WebElement droppable = selenium.findElement(By.xpath("//*[@id='droppable']"));
Actions oAction = new Actions(selenium);
//Performing Drag and Drop operation
oAction.dragAndDrop(draggable, droppable).perform();
System.out.println("Successfully completed the Drag-Drop operation");
}

}



Note:- we can also re-size the control, just need to change syntax a bit 
oAction.dragAndDropBy(resize, 400, 200).perform();

5.How to refresh a application window using Action class?

Code:-

 Actions oAction=new Actions(selenium);
oActions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();


Let’s learn JavaScript Hoisting

When was the last time, you encountered confusing questions on “JavaScript Hoisting” in your interview?

Not very long back if you are looking for change 🙂

Today’s topic is very simple, but most misunderstood concept in our coder’s fraternity.

Lets try to learn sharpen our concepts and be ready to face the interview panel with confidence.

Javascript Hoisting
Hoisting



What is JavaScript Hoisting?


JavaScript Hoisting(Raise Up), in simple words refer to moving declarations to the top.(Like our flag hoisting ceremony in school times ).

Technically it is the default behavior of JavaScript, to shift all the declarations to the top of the function or global scope .


Principle:-


In other words, declaring a variable anywhere in the code is equivalent to declaring it at the top which allows a variable to be used before it is declared. 

However, only the declaration will be hoisted. If the variable is initialized, the current value, at the top of the scope, will initially be set to undefined.
Meaning:-JavaScript only hoists declarations, not initialization.


Example:-

Variable Hoisting

function bar(){
function foo(){}
var a=7;
}

Will be interpreted as:

function bar(){
var a;//initialized to undefined
function foo(){}
a=7; // assignments are not affected by Hoisting
}


Function Hoisting
Note:- Variable name = function name = foo

var foo =3;
function bar(){
foo= 7;
return;
function foo(){}
}
bar();
alert(foo);
will be interpreted as:

var foo =3;// defines foo in global scope
function bar(){
function foo(){} // defines foo in local scope and can be rewritten as “var foo = function(){}”
foo= 7; // overwrites local variable foo
return;
}
bar();
alert(foo);




In JavaScript, functions are the first class objects like strings and numbers which means they are assigned to variables that can be passed to other functions as well.

Explanation:-

  • Function foo() is hoisted first and it will act like var foo = function(){};,as a result a local variable foo is created
  • Local variable will always get precedence over global variable if there are two variables with same name (one in local, another in global).
  • In above example, foo=7; means setting the value in the local scope. So the result of alert will be 3
  • JavaScript does not have block statement scope; rather, it will be local to the code that the block resides within.
  • Declaring variables in a function means that variables declared in a function are accessible within that function, even before they are assigned a value.


How Name Resolution Order works:-

  • Both local and global scope, have the special name this, defined in them , which points the current object.
  • Function scope also has the named arguments , defined in them which are passed to them.

Confused!! Lets comprehend with example,

For example, JavaScript will find the name in the following order when accessing a variable named bar inside the scope of a function.
1.    Use var bar; statement if it is present in current/function scope.
2.    Use function parameter if it is having the name as “bar”.
3.    Use function itself, if its name is “bar”.
4.    Look in the outer scope and repeat the entire process from point 1.

Key Learning’s:

Always declare variables at the top of the scope (function/global) 


How to work with IFrame in Selenium.

Scenario:
Our application has a iFrame control, how we can work with this control using Selenium.

Bird thinking about iframe selenium
Learn to solve the iFrame puzzle in selenium


Solution:-
Lets try to understand iFrame first.

What is iFrame?
An iFrame (or Inline Frame) is an HTML document embedded inside the current HTML document on a browser application. It is utilized to insert content from another source, such as an advertisement, into a Web page. Our application can have multiple frames on a single page, which can be further nested (Frame inside a Frame). This enables updates of parts of a website while the user browses, without making them reload the whole thing. (This is now largely replaced by AJAX)

How it is handled in Selenium?
As we know iFrame works as an independent application inside a parent application .Thus to work with iFrame elements , we need to change the focus of selenium from parent window to the iFrame window(child window).If we are not doing this, selenium won’t be able to identify controls of iFrame and we will face “ElementNotFoundExceptions”.

Principle:-
Selenium WebDriver works with multiple windows(iFrame here) using window handler.It assigns an unique alphanumeric id to each window as soon as the WebDriver object is instantiated. Further with the help of this id it switchs control among several windows. In simple terms, each unique window has a unique ID, so that Selenium can differentiate when it is switching controls from one window to the other.

Syntax:-
Switching to the frame: 

driver.switchTo().frame("frame1");  

                  
Switching back to the parent window: 

driver.switchTo().defaultContent();


Approach:-
Using find element Technique,

//First we will find the iFrame , then we will switch to command.
WebElement frame = driver.findElement(By.Name("frame1"));
// or
WebElement frame = driver.findElement(By.Id("frame1"))
//Now we will switch focus,
driver.switchTo().frame("frame"); ;

  
   
Using Index of the Frame,    

driver.switchTo().frame(0);


0- refers the first child frame.

Using name/id of the frame

driver.switchTo().frame(framename);

Note:-
GetWindowHandle Command , to get the window handle of the current window.
String  hnd = driver.getWindowHandle();

Code:-