Static Keyword in Java

What is Static Keyword in Java?

Static means a field or an method that belongs to the class, rather than to an instance of the class.In simple terms, it means that we can call a static method/field even without creating the object of a  class to which they belongs!.We can have a static method or a static variable.

We have used this concept in our public static void main(String[] args), while using this we never created the object of main method but instead Java virtual machine can call the main method without creating a new application object.

Note:- we cannot use Static with class unlike final keyword.

illegal modifier error on creating static class
Static class is not possible!!

How to access static method/Variable

Syntax:-
ClassName.StaticMethod/Variable Name

Example:-
We would be accessing the static method of class(StartURL) using StartURL.testURL();

Accessing static method by its name in java


Code:-
package Java;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class StartURL {
//Creating Static variable
private static WebDriver driver;
//Creating an Static Method
public static void testURL(String sURL)
{
driver = new FirefoxDriver();
driver.get(sURL);
System.out.println("Inside Static Method");
}

}
package Java;

public class MainTestCase extends StartURL{

public static void main(String[] args) {
//Accessing the Static method without
//creating class object
StartURL.testURL("http://www.uftHelp.com");

}

}



Note:- We can still access the static method or variable by using the instance object of the class, but this is not a good coding practice.In above case we could have done it using :-  

 public static void main(String[] args) {
//Accessing the Static method
//By creating class object
StartURL obj = new StartURL();
obj.testURL("http://www.uftHelp.com");
}

Still Eclipse or other Java IDE’s would generate warning message :-

Static method warning message in Eclipse



Important points:-
1.Static method is associated with a class while non static method is associated with an object.
2.We can use Static + final to create constant value that’s attached to a class.
Example:-

package Java;
public class StartURL {
//Creating Static variable
final static int noOfDays = 365;

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

3.When we create different object of an class, each class contains its distinct copy of instance variable and each is stored in different memory location but incase of static variables, it is shared across the class , which occupies an fixed location in memory.So by using static keyword we are making our program memory efficient.
4.Non static (methods, variables) can not be accessible inside static methods,meaning we can only access  static stuff Inside static methods.
Example:-

Cannot Access non static variable inside a static method of java

Interface in Java

Understanding Interface concept of Java in Selenium

When we first start with selenium automation our very first line of code comes as :-
WebDriver driver = new FireFoxDriver;

Have we ever thought what is the meaning of this code of line …WebDriver driver ?
Simple answer to this is “WebDriver is an Interface,and we are defining a reference variable(driver) whose type is an interface.Now any object we assign to it must be an instance of a class(FireFoxDriver) that implements the interface.”

Confused!!!, no worries lets understand Interface concept in Java first, it would really assist us in clearing our doubts.

Do follow us on FB,G+,Twitter or LinkedIn  to learn more 

What is an Interface?
Interface is like a blueprint of Class. It contains variables and body less methods(Abstract methods), where we just declare methods but we implement them inside the class which inherit Interface.

Note:- Java 8 introduced “Default Method” or (Defender methods), which allows us to add new methods with declaration and definition (like a normal method)to the Interfaces without breaking the existing implementation of these Interface.

Example:-

Public Interface WebDriver()
{

int iNum = 10;
public void get(String URL);

}


Above example just contain the structure of a get method, now a class which would implement this interface need to define the method.

Note:- By default all the variables and methods inside an Interface are public-ally accessible. 

Example:-

Public class FirefoxDriver implements WebDriver()
{
public void get(String sURL)
{
System.out.println("URL="+sURL);
}

}


Now we know that incase of Interface, “If we define a reference variable whose type is an interface,any object we assign to it must be an instance of a class that implements the interface.”

In our example that Class is FireFoxDriver and Interface is WebDriver, so we can say WebDriver driver = New FirefoxDriver();


WebDriver interface implements Firefoxdriver class



Note:- We need to use the Implements Keyword to consume Interface inside a Class.

Lets learn more about an Interface

Interface instance:-
We can create a reference variable of an interface but we can’t instantiate any interface since it is just a contract to be implemented in a Class.

WebDriver driver = New WebDriver …Not allowed, 

cannot instantiate interface in java

but below code is allowed….
Example:-

WebDriver driver = New FireFoxDriver();
driver.get(testUrl);

Creating Interface in Eclipse:-
Lets create a sample interface in Eclipse and implement it inside a Class.
Right click on package and go to -> New -> Interface.

Creating Interface in Eclipse


Important points:-

    1. Class that implements an interface must implement all the methods declared in the interface.Now our FirefoxDriver class should implement all the methods declared inside an WebDriver interface, same is the case with ChromeDriver or IEDriver classes.
    2. While implementing methods, we must follow the exact same signature (name + parameters) as declared in the interface.
    3. We can not instantiate/create object of an Interfacewebdriver driver = new webdriver ();
    4. All the variable inside an interface are by default Final.
    5. Class cannot Extend Interface only Implements it.
    6. Interface an Extend another Interface but then the class which implements the interface need to implemented the methods of both interface .
    7. Class can implement multiple Interface(Remember class cannot extend multiple classes,multiple inheritance in class is not possible)
      Class inherit from multiple Interface

    8. Interface can not hold constructor.
    9. Interface can not hold instance fields/variables.
    10. By default all the methods of Interface are public so no need to provide access modifiers.
    11. An interface can have another interface i.e. known as nested interface. 

Abstract Class v/s Interface 
Abstract class is similar to interface, like we cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.But in abstract class, we can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that are  declared or defined (as default methods) are public. We can implement any number of interfaces unlike abstract class which can extend only one class.


Note:- We could have implemented WebDriver driver = New FirefoxDriver(); as FirefoxDriver driver = new Firefoxdriver();

But we would face problem incase we need to run the same code for chromedriver then we need to create the object as ChromeDriver driver = new ChromeDriver();.

Thus to avoid this we are creating reference of WebDriver and assigning the object of implementing class i.e webdriver driver; driver = new firefoxdriver or driver = new chromedriver();


Understanding important concepts of Java for Selenium

We would be highlighting some of the most vital concepts of Java used in Selenium.Hope it assist our readers to learn and incorporate it while creating the Selenium scripts.

  1. Final Keyword
  2. Interface in Java
  3. Meaning of Static in Java 

Why we use Final Keyword ?

We can use “Final” with a variable, Method or Class

Final variable :-
Example Scenario:-
In the below code we have declared WebDriver as Final but why??

public class LoginPage {
private final WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;

}


Lets understand what is meaning of Final Keyword first!!

  • Final Variable, is nothing but a constant(driver would act as constant above), as we cannot change its value once it is initialized.
  • We need to initialize the value of final variable at the time of declaration,(like final int itest = 10;).We have a exception that we can have final variable uninitialized(blank Final Variable) but  than it must be initialized inside a Constructor (i.e this.driver = driver 😉 the way it is done in our example scenario above.

Now in our example scenario, we have taken webdriver variable as final, so that one’s its value is initialized to the current webdriver instance we don’t want it to change.

Final Method:-
1.We cannot override a final method.
Example:- We have taken TestClassA and TestClassB, where B Extends A, now incase we try to override the method of A in B.

Final method override error in Java

2.But an subclass can call the final method of parent class but not override.Example we can call the add() method below using TestClassB object

Final method can be called in subclass Java


Final Class:-
1.We cannot extend a final Class
Example:- We have made our TestClassA as Final , and we cannot extend this class in TestClassB.

Cannot Extend Final Class in Java


Important points:-
1.All variables inside an Interface are by default treated as final.
2.We need to initialize the final variable value while declaration other option is to initialize it inside a constructor.
3.We cannot override final method.
4.We cannot inherit final class.
5.We cannot declare constructor as final.

Understand Keyword Driven Framework by using UFT – (Part 3)

We are on the last step of completion of our “Keyword Driven Framework“.we hope you are quiet comfortable with our last tutorials on architecture of Keyword Driven Framework-Part 1 and its various components with working code in Keyword Driven Framework- Part 2, before arriving on the final step.Here we are discussing the last component of our framework i.e our Keyword sheet.We would discuss its structure with examples.So that our readers can independently create and design Keyword sheet as per their project requirements.

Do follow us on Fb,G+,Twitter for more topics.

Keyword Sheet:-

Keyword Driven Framework Data Sheet
KeyWord Sheet

Test Details:- It is our Test Step which is performed on the AUT.It adds readablity to our keyword and same message is shown inthe result viewer of UFT.

MainWindow:- It is the parent object of the AUT (Like Browser in Web application)

Screen :- Child objects, here we can separate the hierarchy of objects  by “;”  until our action object.
Example:-
We have object with following hierarchy :- 
Browser(“test”).Page(“test”).Frame(“test”).WebEdit(“test”)

  • Webedit is our action object.
  • MainWindow :- Browser object
  • Screen :- Page Object; Frame object

So thus as child hierarchy increases we need to separate the objects by “;” and add to Screen column.

Keyword:- Operation to be performed on the Action object
Example:- 
1.COMMENT :- This keyword just adds “Test Details” to the result viewer.(Action object is blank here)
2.LAUNCH :- It launches our Browser Application (Action object is blank here)
3.IN:SET  :-It is a input operation of setting a value into edGoogleSearch (Action object)
4.IN:CLICK :- It is again clicking on the button object
5.CHECK:ALT :- It is a Check operation,which tries to match the actual “ALT” property of the action object with the Expected value.
6.SKIPME :- This keyword is just used skip the given step and no action will performed , even no reporting is done for this step unlike “COMMENT” keyword.

Note:- Keyword annotation are user created, we can modify the same as per our  requirement and something which is more meaningful.

Object:- It is our action object(on which UFT would perform operation in the AUT), it can be blank incase no object is required to be passed like “COMMENT’,”LAUNCH”.

Value :- It contains our main parameter that need to be passed to the keyword to perform event on the action object.
Example:- 
1.LAUNCH keyword have value = “iexplore.exe“, thus it opens IE browser
2.IN.SET keyword have value = “uftHelp”, thus it sets this value into the Action object(edGoogleSearch)

Param1/Param2:-
It contains any aditional paramters that need to be passed to the Keyword to achieve the task
Example:-
1.Launch Keyword(refer row-3 in the image above), contains “Param1”, which points to the URL of the application
2.CHECK:ALT Keyword it contains “=” as “Param1”, which is used to compare the value of the Title.

Reporting:-
We can use customized reporting as per the project and management requirements.Here are using Result Viewer in reporting with the help of Reporter.Report Event.

Result Viewer reporting in UFT
Result Viewer for Reporting



Hope this framework enlightens our audience with the basic level architecture and implementation of the Keyword Driven Framework.In our Next post we would we modifying this approach to include data driven framework so that we can achieve a our initial target of designing Hybrid Driven Framework.

Understand Keyword Driven Framework by using UFT – (Part 2)

After our basic overview of Keyword Driven Framework in Part -1 , now we would implement and understand its individual components. Part3 contains the keyword sheet creation and run results.

Test Scenario:- 
We would be using the following scenario to exemplify our Keyword Framework
1.Launch web browser 
2.Search “uftHelp” on “Google”
3.Open the first link of search Result
4.Verify that www.uftHelp.com, page is opened
5.Search any given value on this Tutorial website
6.Close the Application 

Solution Explorer:-
This is how our Framework Solution would look like.

Solution Explorer in UF
Solution Explorer in UFT

TC_01_Search :-Name of our Test Case

We have taken 2 input parameters:
FilePath:- Path of our Excel sheet containing Keywords
SheetName:- Keyword sheet in the Excel

Input Parameters property window UFT
Input Parameters 

How to set input Parameters?

  • Select the Test Case(TC_01_Search) in Solution Explorer
  • View -> Properties
  • Open “Parameters Tab” -> Add -> Add Input Parameter
  • Fill the Name and Default Value , Leave Type as String 

Driver:-
It contains our driving script to control and call the other components of the framework.

Note:- 

  • We tried to add appropriate comments to explain the code,Please contact us or add comments below for any clarification.
  • For clear comprehension of the code try to run the script in debug mode (F11).

You can also follow us on FB,G+,Twitter or LinkedIn for more updates.

Code:-

Option Explicit
'*******************Variable Declaration-Start*********************
'File Path for Test Sheet
Dim sTestFilename
'Taking file path from Test Arguments
sTestFilename = TestArgs("FilePath")
'Test Sheet Name
Dim sSheetName
sSheetName = TestArgs("SheetName")
'Excel Objects
Dim objExcel,objWB,objWS
'*******************Variable Declaration-Ends***********************

'Killing any Running Excel Processes
SystemUtil.CloseProcessByName "Excel.exe"
'Killing Browser Instance of Chrome or IE
'We can add other browsers also like firefox
SystemUtil.CloseProcessByName ("iexplore.exe")
SystemUtil.CloseProcessByName ("chrome.exe")
'Saving the Total Row counts in Test Data sheet into Enviornment Variable
Environment("TotalRowCount") = fn_ExcelGetRowCount(sTestFilename,sSheetName)

'Setting the Value of Starting ROW = 2
'We have taken 1 row for header fields in the KeywordSheet
Environment("StartRow") = 2
'Execute Each row till the End of Test Data
Do While Environment("StartRow") <= Environment("TotalRowCount")
'Function call to handle the Keyword Sepearation
fn_SeperateKeywords
Loop

'Killing the working Excel Processes
'It is closing the Our Testcase Excel sheet
SystemUtil.CloseProcessByName "Excel.exe"




Explanation:-

  • Driver script fetches the input FilePath and SheetName from input parameters of the test(As explained above)
  • Closes any opened instance of Excel or browser(chrome or IE).We have various techniques to kill a browser instance from task manager.
  • It further calls the Excel lib function to fetch the number of rows in the Keyword sheet, then it iterates from the 2nd row of the sheet(1st is for headers) and Calls Main Lib to work with keywords.
  • When run is completed for all the rows, it closes the working excel (Keyword Sheet, which is opened while fetching data)

How to fetch date from a Excel file.

Object Repository:-
Common_OR, it is our shared object repository which contains the objects for the above Test scenario.

Object Repository view in Keyword Framework
OR View

We have followed the below naming conventions for objects:-
Note:- it is crucial to use the naming conventions as it is implemented in the framework to segregate the object type based in the first 2 characters of the object name.

Keyword
Object
br
Browser
pg
Page
im
Image
ln
Web Link
bt
Web Button
ed
Web Edit
el
Web Element
rd
WebRadioGroup

Function Libraries:-
It is the container for our reusable functions, we would be calling these functions to do action on the object in our AUT(Application under Test)

Keyword Lib :-

Toolbox view of Functions in UFT
Keyword Functions

Code:-

'*******************************************Function*********************************
'Function Name:- fn_Launch
'Function Description:- Opens a given browser type and redirects to given URL
'Input Parameters:- Browser exe, URL
'Output Parameters:- N/A
''***********************************************************************************
Public Function fn_Launch(sBrowser,sURL)
'Launching Browser
systemutil.Run sBrowser,sURL,"","Open",3
End Function

'*******************************************Function*********************************
'Function Name:- fn_Close
'Function Description:- To close the running Application
'Input Parameters:- Application Image Name (like chrome.exe)
'Output Parameters:- N/A
''***********************************************************************************
Public Function fn_Close(sProcess)
'Killing the running process
systemutil.CloseProcessByName(sProcess)
End Function

'*******************************************Function*********************************
'Function Name:- fn_InputData
'Function Description:- Doing Keyword level input action on the Application
' like Set,Click
'Input Parameters:- Mainwindow,Sub screen,Keyword(like Set),Main object
' (like webedit), Value
'Output Parameters:- N/A
''***********************************************************************************
Public Function fn_InputData(sMainWindow,sScreen,sKeyword,sObject, sValue)
Dim oObject, oParent
On Error Resume Next
Err.Clear
Set oObject = Nothing
Set oParent = Nothing
'Creating the Parent object Heiarchy
'Example :- browser("brGoogle").page("pgGoogle")
Set oParent = fn_CreateObjMain(sMainWindow, sScreen)
'Creating the child object Heiarchy,i.e. our object on which action is taken
'Example:-browser("brGoogle").page("pgGoogle").webedit("edTest")
Set oObject = fn_CreateObjTree(oParent, sObject)
'Adding Sync incase of Page object
If oParent.GetROProperty("micclass") = "Page" Then
oParent.Sync
End If
'Doing the operation on the Object
Select Case UCase(sKeyword)
Case "CLICK": oObject.Click
Case "SUBMIT": oObject.Submit
Case "SET": oObject.Set Cstr(sValue)
Case "SET_SECURE": oObject.SetSecure Cstr(sValue)
Case "SELECT": oObject.Select Cstr(sValue)
Case "EXTENDSELECT": oObject.ExtendSelect Cstr(sValue)
Case "SELECTINDEX": oObject.Select Cstr("#"&sValue)
Case "TYPE": oObject.Type Cstr(sValue)
Case "FIRE_EVENT": oObject.FireEvent Cstr(sValue)
Case "SEND_KEYS": oObject.Click : Wait 1:SendKeys Cstr(sValue)
Case "CLOSE": oObject.Close : Wait 2
Case Else
Reporter.ReportEvent micFail,"Input type is not recognised,"&_
"Inside fn_InputData function ", sInputOperation
'ExitTest
End Select
'Incase of Error
If Err.Number <> 0 Then
Reporter.ReportEvent micFail, "Error Happened inside fn_InputData "_
, Err.Description
On Error GoTo 0
'Exit test run
'ExitTest
End If

Set oParent = Nothing
Set oObject = Nothing
End Function

'*******************************************Function*********************************
'Function Name:- fn_CheckData
'Function Description:- To check the Expected property of the object like innertext
' should match for the object
'Input Parameters:- Mainwindow,Sub screen,Keyword(like value,innertext),Main object
' (like webedit),Value,comparision type (=,<>,>)
'Output Parameters:- N/A
''***********************************************************************************
Function fn_CheckData(sMainWindow,sScreen,sProperty,sObject, sValue,sParam1)
Dim sExpectedValue,sActualValue,sCompareType
'Expected value to be compared
sExpectedValue = sValue
'Comparison factor like '=','<>'
sCompareType = sParam1
On Error Resume Next
Err.Clear
Set oObject = Nothing
Set oParent = Nothing
'Creating the Parent object Heiarchy
'Example :- browser("brGoogle").page("pgGoogle")
Set oParent = fn_CreateObjMain(sMainWindow, sScreen)
'Creating the child object Heiarchy,i.e. our object on which action is taken
'Example:-browser("brGoogle").page("pgGoogle").webedit("edTest")
Set oObject = fn_CreateObjTree(oParent, sObject)
'Adding Sync incase of Page object
If oParent.GetROProperty("micclass") = "Page" Then
oParent.Sync
End If

'Actual value of the object
sActualValue = oObject.getroproperty(sProperty)

'Taking the comparision based on the comparison Type
Select Case sCompareType
Case "=":
If Ucase(Trim(sExpectedValue)) = Ucase(Trim(sActualValue) )Then
Reporter.ReportEvent micPass,"Checkpoint Passed.","Expected value of '"_
&sProperty&"' = '"& sValue&"' found in the application"
End If

Case "<>":
If Ucase(Trim(sExpectedValue)) <> Ucase(Trim(sActualValue) )Then
Reporter.ReportEvent micPass,"Checkpoint Passed.","Expected value of '"_
&sProperty&"' = '"& sValue&"' Not found in the application"
End If
Case ">":
If Ucase(Trim(sExpectedValue)) > Ucase(Trim(sActualValue) )Then
Reporter.ReportEvent micPass,"Checkpoint Passed.","Expected value of '"_
&sProperty&"' = '"& sValue&"' found greater in the application"
End If
Case else
Reporter.ReportEvent micPass,"Error Happened inside 'fn_CheckData'",_
"Invalid Comparator"&"Type = '"&sCompareType&"'"
End Select
'Incase of Error
If Err.Number <> 0 Then
Reporter.ReportEvent micFail, "Error Happened inside 'fn_CheckData' "_
,Err.Description
On Error GoTo 0
'Exit test run
'ExitTest
End If
fn_CheckData = True
End Function


Main Lib :-

Keyword functions in UFT
Main Functions

Code:-

'*******************************************Function*********************************
'Function Name:- fn_SeperateKeywords
'Function Description:- Function to fetch the cell data from Test Sheet
'Input Parameters:- N/A
'Output Parameters:- N/A
''***********************************************************************************
'Function to separate the Keywords
Public Function fn_SeperateKeywords
'Variable Declaration
Dim sTData
Dim sTestStep, sMainWindow, sScreen,sKeyword,sObject,sValue
Dim sParam1, sParam2
'Creating an Array from data in each Row
sTData = fn_ExcelReadRowData(objWS,sTData, Environment("StartRow"))
'Taking the values from the Array sTData
sTestStep = sTData(0)
sMainWindow = sTData(1)
sScreen = sTData(2)
sKeyword = split(sTData(3),":")
sObject = sTData(4)
sValue = sTData(5)
sParam1 = sTData(6)
sParam2 = sTData(7)

'Incase Keyword is SKIPME, UFT will skip that Row Run
If sKeyword(0) <> "SKIPME" Then
Select Case UCase(sKeyword(0))
'Keyword to Launch Application
Case "LAUNCH": fn_Launch sValue,sParam1
'Keyword for adding Wait
Case "WAIT": Wait sValue
'Keyword for adding Comment in output results
Case "COMMENT": Reporter.ReportEvent micInfo, " < Comment given by User:>", sTestStep
'Keyword for working with Input operations
Case "IN": fn_InputData sMainWindow,sScreen,sKeyword(1),sObject, sValue
'Keyword to check property of the Object
Case "CHECK": fn_CheckData sMainWindow,sScreen,sKeyword(1),sObject, sValue,sParam1
'Keyword to Kill running Process
Case "CLOSE": fn_Close sValue
'Incase of mismatch of Keyword
Case Else : Reporter.ReportEvent micFail, "UnKnown Keyword" ,_
"Keyword Not Recognised: " & Cstr(sKeyword)
End Select
End If
'Increasing the Row Counter to fetch data from the next Row in Excel
Environment("StartRow") = Environment("StartRow")+1
End Function

'*******************************************Function*********************************
'Function Name:- fn_CreateObjMain
'Function Description:- Calls fn_CreateObjTree to get the Parent hierarchy of the object
'Input Parameters:- sWindow(Parent Object),sScreen(Child object)
'Output Parameters:- N/A
''***********************************************************************************
Function fn_CreateObjMain(sWindow, sScreen)
Dim sObjects, iObjectCount
Set fn_CreateObjMain = Nothing
'Creating the Parent tree object
'Example:- browser("brGoogle")
Set fn_CreateObjMain = fn_CreateObjTree(fn_CreateObjMain, Cstr(sWindow))
'If Screen value is non empty, then creating the sub tree
'Example:- browser("brGoogle").page("pgGoogle")
If Cstr(sScreen) <> "" Then
'This is required incase of further node inside a sub tree
'Example:- browser("brGoogle").page("pgGoogle").frame("frGoogle")
sObjects = Split(sScreen, ";")
'Looping till the end of nesting on the Screen column
For iObjectCount = 0 To Ubound(sObjects)
'Calling the object tree function
Set fn_CreateObjMain = fn_CreateObjTree(fn_CreateObjMain, Cstr(sObjects(iObjectCount)))
Next
End If
'Incase of errors
If fn_CreateObjMain Is Nothing Then
Reporter.ReportEvent micFail ,"Error Happened inside fn_CreateObjMain",_
"The parent object could not be located" & sWindow & " " & sScreen
End If
End Function

'*******************************************Function*********************************
'Function Name:- fn_CreateObjTree
'Function Description:- Finds the childobject and attaches it to the parent hierarchy
'Input Parameters:- objParent(Parent object),sObjectName(Name of child object
' in object repository)sWindow(Parent Object),sScreen(Child object)
'Output Parameters:- N/A
''***********************************************************************************
Function fn_CreateObjTree(objParent, sObjectName)
'Taking the left value of the objectname
'Example:- Taking 'br' from 'brGoogle' object
Select Case LCase(Left(sObjectName, 2))
Case "br": Set fn_CreateObjTree = Browser(sObjectName)
Case "dl": If objParent Is Nothing Then
Set fn_CreateObjTree = Dialog(sObjectName)
Else
Set fn_CreateObjTree = objParent.Dialog(sObjectName)
End If
Case "pg": Set fn_CreateObjTree = objParent.Page(sObjectName)
Case "rd": Set fn_CreateObjTree = objParent.WebRadioGroup(sObjectName)
Case "ln": Set fn_CreateObjTree = objParent.Link(sObjectName)
Case "im": Set fn_CreateObjTree = objParent.Image(sObjectName)
Case "fr": Set fn_CreateObjTree = objParent.Frame(sObjectName)
Case "ed": Set fn_CreateObjTree = objParent.WebEdit(sObjectName)
Case "bt": Set fn_CreateObjTree = objParent.WebButton(sObjectName)
Case "el": Set fn_CreateObjTree = objParent.WebElement(sObjectName)
Case "ls": Set fn_CreateObjTree = objParent.WebList(sObjectName)

Case Else
Reporter.ReportEvent micFail, "Error Happened inside 'fn_CreateObjTree' " ,_
"Object type is not found: " & sObject
fn_CreateObjTree = False
End Select
End Function



Excel Lib :-

Toolbox view of Functions in UFT
Excel Functions

Code:-

'Delcaring common excel objects
Dim objWB,objWS,objRange
'*******************************************Function*********************************
'Function Name:- ExcelGetRowCount
'Function Description:- Returns No. of rows in the Test Data Sheet
'Input Parameters:- Excel file path,Sheet Name
'Output Parameters:- No. of Rows
''***********************************************************************************
Public Function fn_ExcelGetRowCount(sTestFilename,sSheetName)
'Open Excel Connection
Set objExcel= CreateObject("Excel.Application")
objExcel.Visible = False
objExcel.EnableEvents = False
objExcel.DisplayAlerts = False
'Open WorkBook
Set objWB = objExcel.Workbooks.Open(sTestFilename)
'Refering the Sheet
Set objWS = objWB.Worksheets(sSheetName)
'Taking the Range
Set objRange = objWS.Range("A1").CurrentRegion
fn_ExcelGetRowCount = objRange.Rows.Count
Set objRange = Nothing
End Function


'*******************************************Function*********************************
'Function Name:- fn_ExcelReadRowData
'Function Description:- Reading the Row and returns Each cell in a Array
'Input Parameters:- N/A
'Output Parameters:- N/A
''***********************************************************************************
Public Function fn_ExcelReadRowData(objWS, sData, iRow)
'Variable declaration
Dim iCount
'Fetching the Excel range
Set objRange = objWS.Range("A1").CurrentRegion
ReDim sData(objRange.Columns.Count)
For iCount = 1 To objRange.Columns.Count
sData(iCount-1) = CStr(objRange.Rows(iRow).Columns(iCount).Value)
Next
'Destroying object
Set objRange = Nothing
fn_ExcelReadRowData = sData
End Function


Recovery Scnearios:-

ApplicationCrash:- we have created Recovery Scenario to handle exceptional crash of our AUT.

How to create Recovery Scenario:-

  • Resources -> Recovery Scenario Manager -> New Scenario

Trigger Event:– Is crashing of any browser (Chrome or IE)

Trigger Event in Recovery Scenario
Trigger Event

RecoveryOpeations:– Close the Browser window

Recovery Operation in UFT
Recovery Operation

Post-Recovery Operation :- Re-run the test 

Post recovery Operation in Recovery Scenarion
Post-Recovery Operation UFT

Understand Keyword Driven Framework by using UFT – (Part 1)
Understand Keyword Driven Framework by using UFT – (Part 3)

Understand Keyword Driven Framework by using UFT – (Part 1)

Framework is to automation as beauty is to Nature. Amazing thing about our mother nature is that it brings happiness and rejuvenates our energy level, similarly framework makes our automation task more manageable and brings elegance in coding.Today we would be focusing on the fundamental architecture of the framework. We would be beginning with Keyword driven framework and then we would polish it as our Hybrid framework.

We won’t be discussing much of theory but would be doing lot of coding 🙂

We have divided this topic into 3 Part Tutorial :-

  1. Part1 (Current post, it contains the Working copy of the code + Architecture of the Framework)
  2. Part2(It consists of Driver Script + Function Lib’s + Recovery Scenario + Object Repository)
  3. Part3(Keyword Sheet creation + Run Results)

Working hard for something we don’t care about is called stress; working hard for something we are passionate about is called Love”. So in case one loves automation we would always we improving framework. We always believe that no framework is perfect and everything is requirement based.Do share your comments and knowledge so it is beneficial for our fellow coders,We can also be in touch through Fb,G+,Twitter or Email.

Note: – In our previous post we discussed various components of framework but in the below code we are just implementing the basic flow. we can further segregate them as per our requirement,to add more modularity.

Please download the code and follow the tutorial to get hold of this framework.


Note:- After downloading the coding -> Extract the zip files -> open the “KeywordApproach” folder -> paste inside c:Temp -> open the Driver script in UFT/QTP.

Keyword Driven framework folder structure
Folder structure of the Keyword Driven Framework



Key Components:-

Driver Script:-
This is our driving component, it contains the call to other components (Functions)

Function Library:-
This contains our functions, which we have segregated based on the operation level:-

  • Main Lib: – This contains our framework level functions, which further call the other libraries.
  • Keyword Lib: – This contains the functions which defines our Keywords in the Keyword Sheet.
  • Excel Lib: – This library contains the Excel level functions like to fetch data or write data into excel.

Keyword Sheet:-
It consists of our keyword data, which are taken as input to our framework to initiate action on the application.

Recovery Scenario:-
We have added the “ApplicationCrash” recovery scenario, which re-run our test, incase our application(we have taken chrome and IE) crashes.

Object Repository:-
Repository of our objects used in the framework.
Note: – We would be using special naming conventions for each type of object, this is also part of our framework.

Flow Diagram:-

Flow diagram for Keyword Driven Framework
Flow of Keyword Driven Framework

1.Driver Script interacts with Excel Lib.
2.Excel Lib fetch number of rows to be run from “Keyword Sheet” i.e our data sheet.
3.Driver interacts with Main Lib
4.Main Lib with the help of Excel Lib it fetch the data from “Keyword Sheet” for the first row into a array
5.Keyword lib creates the heiarchy of object like browser.page.object
6.Object is fetched from OR
7.Final action is performed on the Application under Test (AUT)

Note:-RS inthe flow diagram, refers to recovery scenario to handle exceptional scenarios.

Summary:-
So far we did basics about the key components of the  Framework and then we integrated them in a flow to form a Keyword Driven Framework architecture, in our next post we would be creating each of these individual components to get a workable copy of the “Keyword Driven Framework

Understand Keyword Driven Framework by using UFT – (Part 2)
Understand Keyword Driven Framework by using UFT – (Part 3)
Hybrid Framework!!

Do follow us on Fb,G+,Twitter for more topics.

Javascript Interview Questions(Part 3)

Here comes more JavaScript questions with solutions.

Learn more share more, do follow us on FB, Twitter , G+ or LinkedIn.

Javascript interview Questions
What does NaN function do?
The isNaN() function determines whether a value is NaN or not. Coercion inside the isNaN function has interesting rules.When the argument to the function is not isNaN() of type Number.The value is first coerced to a Number. The resulting value is then tested to determine whether it is NaN.

Thus for non-numbers that when coerced to numeric type result in a valid non-NaN numeric value (notably the empty string and Boolean primitives, which when coerced give numeric values zero or one), the “false” returned value may be unexpected; the empty string, for example, is surely “not a number.” 

Examples:


isNaN(NaN);       // true
isNaN(undefined); // true
isNaN({}); // true

isNaN(true);      // false
isNaN(null); // false
isNaN(37); // false

// strings
isNaN("37"); // false: "37" is converted to the number 37 which is not NaN
isNaN("37.37"); // false: "37.37" is converted to the number 37.37 which is not NaN
isNaN(""); // false: the empty string is converted to 0 which is not NaN
isNaN(" "); // false: a string with spaces is converted to 0 which 
                         is not NaN

// dates
isNaN(new Date()); // false
isNaN(new Date().toString()); // true

isNaN("blabla") // true: "blabla" is converted to a number.
// Parsing this as a number fails and returns NaN



falsy: In javascript 6 things are falsy and they are- false, null, undefined, ”, 0, NaN

NaN in JavaScript
falsy type


truthy: There are only two truthy things- true and everything that is not false

JavaScript true type in NaN Function
true type


What will be the output of the following JS codes?

1.
var b = 0.6
var c= 0.2
(a-b) == c ??

false because float result will always be different

2. ‘ ‘ == 0 ??

It will convert string to number and then perform comparison . If we blank string to number, it will return zero.
So it becomes 0 == 0 ,which will return true

3. [ ] == 0; ??

It will convert []to number and then perform comparison . If we blank [] to number, it will return zero.
You can check this by Number([]) will return  0.
So it becomes 0 == 0 ,which will return true

4. [ ] == [ ] ??

false because both will have different memory pointers.

5. null == null / null=== null??

true

6. null == undefined ??

true

7. null === undefined??

false. Because both have different types.
typeof(null) > object (It is a bug and cannot be fixed because it will break
typeof(undefined) > undefined

8. null instanceOf object ?? 
it will throw an error

9. Is ‘false’  return false?

No ,Because it is a string with length greater than 0.Empty string return false

10. 
Is ‘ ‘ return false?

No ,Because it is a string with an empty space.

11. What is the output of void(2+3)?
It will throw an error.

12. [0] == true

False

//How it works
//convert boolean using toNumber
[0] == 1
//convert object using toPrimitive
//[0].valueOf() is not a primitive so use
//[0].toString() –> “0”
“0” == 1
//convert string using toNumber
0 ==1 –> False


13. “ufthelp” == true

False

//How it works
//convert boolean using toNumber
“ufthelp” == 1
//convert string using toNUmber
NaN == 1 –> False


 

Difference between null and  undefined? 
null means empty or non-existent assignment value which is used by programmers to indicate “no value”. null is a primitive value and you can assign null to any variable.
Ex:
var test_var = null;
alert(test_var); //show null
alert(type of test_var); //shows object
Note: null is not an object,it is a primitive value.Sometimes people assume it wrongly that you can add properties to it because it typeof(null) returns “object”.

undefined means ,undefined means a variable has been declared but has not yet been assigned a value.
Ex:
var test_var;
alert(test_var); //show undefined
alert(type of test_var); //shows undefined


Remember,undefined is a type with exactly one value and that is undefined.You cannot change the value of it by assigning a new value.

What are the scenarios to get undefind?

  • A declared variable without assigning any value to it.Ex: var a;
  • Implicit returns of functions due to missing return statements
  • Return statements that explicitly do not return anything
  • Function parameters that are not passed 
  • Lookups for non-existent properties that do not exist
  • Anything that has been set to undefined
  • Any expression in the form of void

  Deep dive into null

Synchronization in UFT

We are already done with the synchronization in selenium, today we would discussing the same in UFT.Before starting with the synchronization we would recommend to use Exist,WaitProperty,Sync rather than using Wait.

1.wait
This is used when we want UFT to wait for the specified time, so that AUT completes its current operations.It is like pausing the script run for the given amount time(Same like Thread.sleep)
Syntax:- Wait (seconds)
Example:- wait(2)
Given script will pause for 2 seconds.
Note:- if we don’t pass any value  like wait()
it Will generate runtime error.

Wrong Number of Arguments Wait in UFT
Wait,generated Error for missing Time value

Using Wait is not considered as good coding practice, because it is like pausing the script independent of any condition and UFT would wait even if the process for which wait was applied have been completed.We can still use it if nothing from the below properties or methods works out , or we are sure that process will always takes a given amount of time.

2.waitproperty
Is it used to Wait until the the given object property achieves the specified value in the given timeout else it continues to the next step.
Syntax:-object.WaitProperty(PropertyName, PropertyValue, [TimeOut])
Note:- Timeout(milliseconds) is optional,incase it is not provided default synchronization timeout is taken(File->Settings->Run->Object synchronization timeout)
Return Type:- Boolean (True incase property value is achieved in the given Timeout)
Example:-

'To wait for 30 seconds for the the Home link to be loaded 
Set obj = Browser("CreationTime:=0").Page("Index:=0").Link("text:=HOME","html tag:=A")
If obj.WaitProperty("attribute/readyState", "complete", 3000) Then
obj.Click
EndIf


3.exist Property
It instructs UFT to wait for a specified object to appear. 
Syntax:-
Object.Exist(Timeout)
Return Type:-Returns a boolean value indicating whether or not an object currently exists
Note:- Timeout(seconds) is optional,incase it is not given it would take the default synchronization timeout (File->Settings->Run->Object synchronization timeout)
Example:-

'Code to wait for 30 seconds for the Link to exist
Set obj = Browser("CreationTime:=0").Page("Index:=0").Link("text:=HOME","html tag:=A")
If obj.Exist(30) Then
obj.Click
End If


4.sync Method(Only for Web AUT)
Waits for the browser to complete the current navigation.
Syntax:-
Object.Sync
Example:-

'Waits for the Page to load
Browser("CreationTime:=0").Page("Index:=0").Sync


How to modify Default Timeout values:-
Note:- Default ‘object’ sync time is 20 seconds and Browser ‘Navigation’ sync is 60 seconds
Sync:-
File > Settings > Web pane

Browser Navigation Timeout in UFT
Changing Browser Navigation Time 

Exist,WaitProperty:-
File->Settings->Run->Object synchronization timeout
We can always play with the default synchronization time that UFT takes for Exist,WaitProperty or by default before it throws error to the user.

Object Synchronization Timeout in UFT
Changing Object Sync in UFT

Learn UFT
Learn Selenium

All about Locators in Selenium

Locators in Selenium?

When we created our first IDE script, we found that Editor comes with the tabular structure with 3 columns namely Command, Target and Value.
This structure is used by selenium core to simulate user actions on the application under test(AUT).Just a reminder of things again we have :-

Command:Is our action on the AUT like Set
Target:Is our control on which action need to be performed like Textbox
Value:It signifies the value that need to be associated with the target using our command like UserName

Now coming to our main point, what is locator exactly?

Locator: – These are used by Selenium to find and match the elements of our AUT with which it needs to perform some action(like clicking, typing, selecting, verifying).It is used in Target column of Selenium IDE.

In simple words it  tells Selenium which HTML element of our application  a command has to perform the action.

Locating Principle:-
locatorType=location

Note: – The locator type can be omitted in many cases(like identifier,Xpath,dom)

Locator Type:-
Note:Every object(control) visible on a webpage is a “WebElement”.  
Selenium has different ways of locating controls (web elements).

  • Identifier
  • Id
  • Name
  • Link
  • DOM
  • XPath
  • CSS

Note:- One recommendation to cross verify that correct locator is used , we can use Find feature(we have used the same in the below examples) in Selenium IDE, it is similar to Highlight in UFT object Spy.

1.Identifier:-
The identifier locator strategy is used by default in Selenium. It works with the id and name attributes of the html tags. It will look for the first element that has the specified id .If no element has a matching id attribute, then the first element with a name attribute matching the location will be used. Personally we would avoid this way of locating elements as it can be ambiguous.

Identifier – ID(1st preference ) -> Name(2nd Preference)

Example:-
Prerequisites:-Please open the linkhttp://www.ufthelp.com/p/testpage.html” in Firefox and try to inspect the “UserName” textbox.

Solution:-Identifier is UserName, as we know that it works on ID and Name, so when both are given it chooses ID to find the match.

Identifier locator in selenium
Finding Identifier Value 


Verify:-Lets verify it in IDE , if it is able to highlight the element(Background of corresponding element changes yellow) it means our identifier value is correct .

Finding element using Selenium IDE
Finding element using Selenium IDE


Other Examples:-
Password Textbox : password (which is Name attribute as ID is missing)

Quiz1:- What is the identifier value of SignIn Button on the same page?

2.ID:-
This approach is considered superior compared to other locators, provided our web application adheres to the W3C specification (that is, all id’s on a page are unique). Unfortunately there are many cases when an element does not have an id (or the id is somehow dynamically generated and unpredictable). In these cases we will need to use an alternative locator strategy; however it may be worth asking the developers of the web application if they can add a ids to a page controls specifically for testing. It’s usually a trivial task for them and the robustness of whole tests will benefit them too.

Example:-
We can use the above example for locating the element (username Textbox) but this time using ID locator rather than following identifier approach.

Solution:- id = “userName” (we found above)
Verify:- We have to use the locatortype & location while working with ID , not like identifier where we can directly use the location value.

ID locators in Selenium
Locating element using ID locators



3.Name:-
Locating elements by name are very similar to locating by ID, except that we use the “name=” prefix instead.

Note:If multiple elements have the same value for a name attribute, then we can use filters to further refine your location strategy. 

Example of filters:“value” (default filter) , index.

Example:
Without Filter:-We would use name property to identify the element.

Name locator in Selenium
Locating element by Name



With Value filter:-
We have radio buttons with the same name but different values , so we would use value filter

Name with value filter as Locators in Selenium
Name = Automation value = Selenium 


With index filter:-
Note:-Index starts with 0

Name locators with Index filter in Selenium ide
index=0, refers to “Selenium” radio button

Quiz2:-What can be index value incase we want to refer to the “UFT” element.

Important: – The above locators(ID,Name) are independent of the element type and location(they are attribute based, rather than structure) in the tree (UI) and thus if the developer moves the element or changes its type, Selenium can still locate it.

4.Link:-
This approach uses a hyperlink in the web page to locate the element by using the text of the link.

Note:-If two links with the same text are present, then the first match will be used.

Example:- we have link with name “LearnMore”, so we would use it as locator (Link=LearnMore)

Link Locator in Selenium

5.DOM:-
The Document Object Model (DOM), in simple terms, is the way by which HTML elements are structured. Selenium is able to use the DOM structure in accessing page elements.

Note:-Since selenium core is able to interpret the dom as document so we generally remove the locator type and directly use the location value.(Thus we can omit DOM as locator Type and use directly the location value)

We implement it using locator as getElementById or getElementsByName.
For more on DOM

Example:-
We can locate password object by its id, using getElementById
we can either use dom=document.getElementById(“password”) or direct value as we used in below image.

DOM locators example selenium ide


6.XPath:-

XPath is the language used when locating XML (Extensible Markup Language) nodes. While DOM is the recognized standard for navigation through an HTML element tree, XPath is the standard navigation tool for XML; and an HTML document is also an XML document (xHTML).

Note:-It can access almost any element, even those without class, name, or id attributes.But it relies on browsers engine and its value can vary across browsers. Thus it is not recommended for cross-browser testing.

More on XPath 
XPath standards

Word of Caution: Before implementation we can make sure that its value is not varying, this can be done by testing a same control for the the same page on both the browsers. Launch “Firebug for FF” and “F12 Developer Tools for IE”. And now try to find any one element on both by following the Xpath. We are coming on tutorial on finding XPath.

Types:– 
Absolute and Relative XPath.(This one is recommended )

Absolute XPaths(prefixed with a “/”)contain the location of all elements from the root (html) and as a result are likely to fail with only the slightest adjustment to the application. 
But Relative XPath(prefixed with a “//”), by finding a nearby element with an id or name attribute (ideally a parent element) we can locate your target element based on the relationship. This is much less likely to change and can make our tests more robust.

xPath v/s CSS Locator Selenium
xPath v/s CSS Locator


Example:-
Note:- we have already discussed about various xpath tools available for browsers.

Let us identify the x-path of dropdownlist using FirePath (addon to Firefox)

xpath locator in selenium
X-path is calculated using FirePath for “select” dropdown list


7.CSS:-
CSS (Cascading Style Sheets) is a language which is used for beautification of HTML controls  like button should have green color.

CSS uses Selectors for binding style properties to elements in the document. These Selectors can be used by Selenium as another locating strategy.
Locating by CSS Selector is more complicated than the previous methods, but it is the most common locating strategy of advanced Selenium users because it can access even those elements that have no ID or name.(Like X-Path)


Example:- Using CSS ID, 

CSS Locator ID example Selenium IDE

Quiz3:-What would be value of CSS locator incase we have class=password, instead of id=password in above image.
What is ID/Class in CSS  

Difference between ID/Class

Note:- XPath can walk up the DOM (e.g. from child to parent is possible), whereas CSS can only traverse down the DOM (e.g. from parent to child)

Recommended Priority:-

Please try to follow the priority order as ID > Name > CSS >XPath

For more comprehensive structure for DOM,XPath and CSS refer this link

Answer to Quiz:-
Quiz1 :- SignIn
Quiz2:- Index=1
Quiz3:- css=input.password

Screenshot using Selenium

Scenario:-How we can capture error Screenshot while working with Selenium?

Taking Screenshot using PhotoCamera
Taking Screenshot of nature using Camera


Solution:-
We would achieve it using the TakeScreenshot Interface.

Syntax:-


1.Capture Screenshot

File sScreenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);


OutputType.FILE:- We have used Interface Output and we have taken the screenshot as “File” type

we can also take screenshot as Byte and  base64 data
Example:-

String screenshotBase64 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.base64);


getScreenshotAs:– Method that Captures the screenshot
sScreenshot:- It holds a temporary  file that will be deleted once the JVM exits. Thus in the next step we would be saving this file.

2.Saving Screenshot by making a copy of this file.


Creating the Copy of Screenshot file and Saving it on required destination path and with given name.
For this we have used copyFile(source,target) method of the FileUtils class

FileUtils.copyFile(sScreenShot, new File("E:\screenshot.jpg"))


Code:-

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;

public class ScreenShot {
private static WebDriver driver;
@Test
public void launch() throws Exception {
//Luanch browser
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.uftHelp.com");
//Making the code to fail
try{
driver.findElement(By.id("uftHelp")).sendKeys("Selenium");
}
catch (Exception e){
//Capture Screenshot on error.
ScreenShot();
}
}

//Function to capture Screenshot
public void ScreenShot() throws Exception
{
//Taking the Screenshot
File sScreenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//Saving the Screenshot
FileUtils.copyFile(sScreenShot,new File("E:\screenshot.jpg"));

}

@AfterTest
public void afterTest() {
//Closing the browser
driver.quit();
}
}


Output:-

We can open the path and observe the created screenshot.

Happy learning 🙂



How to implement highlight in Selenium