Tuesday 20 May 2014

How to connect SQL server using QTP script


1) We should know the below details before establish database connection with SQL server.


Provider = SQLOLEDB.1  (Default for all SQL server connection)
Server   = Server_Name
uid = User_ID
Password = Password for login into SQL server.
Database = Name of the database


2) QTP dont have the built-in function for access SQl server. So we can use access the data in SQL server by using ADODB connection. SO we should create object for ADODB connection and Recordset,

Set objcon=CreateObject("ADODB.Connection")
Set objrs=CreateObject("ADODB.RecordSet")

3) Establish database connection by using connection string

Syntex : 

objcon.open "Provider= Provider name (SQLOLEDB.1);Server=server_Name;uid=User_ID;Password=User_Password;Database=Database_Name;"

Example:

objcon.open "Provider=SQLOLEDB.1;Server=SQLServerName;uid=arunrajvdm;Password=arunrajvdm;Database=arunrajvdmdatabase;"

Here,

Provider = SQLOLEDB.1  (Default for all SQL server connection)
Server   = SQLServerName
uid = arunrajvdm
Password = arunrajvdm
Database = arunrajvdmdatabase


4) Execute Query

Syntex:

objrs.open "SQL_Statements",object of ADODB connection(objcon)

Example:

objrs.open "Select * from Emp",objcon


5) Access the data from database by using column_Name

we can use Fields property of Recordset object.

Syntex :

objrs.Fields("Column_Name")

Example

objrs.Fields("First_Name")



Sample Script:

Extracting the data from SQL Server database and update into the Excel


Set xl=CreateObject("Excel.Application")
Set xlwb=xl.Workbooks.Open("E:\SQLConnection.xls")
Set xlws=xlwb.Worksheets("TestData")

Set objcon=CreateObject("ADODB.Connection")
Set objrs=CreateObject("ADODB.RecordSet")

objcon.open "Provider=SQLOLEDB.1;Server=SQLServerName;uid=arunrajvdm;Password=arunrajvdm;Database=arunrajvdmdatabase;"
objrs.open "Select * from Emp",objcon

i=1
While not objrs.EOF
 xlws.Cells(i,1)= objrs.Fields("Emp_Name")
 objrs.MoveNext
 i=i+1
Wend


objrs.Close
Set objrs=nothing
objcon.Close
Set objcon =nothing

xlwb.Save
xl.Quit

Set xlws=nothing
Set xlwb=nothing
Set xl=nothing

Thursday 15 May 2014

Generate Random Number with in given range using selenium webdriver




1) we can use java.util.Random class for generate random number.

2) nextInt(n) method used to generate any number from 0 to n.

Ex:

Random rg = new Random();
for (int idx = 1; idx <= 1000; ++idx){
int randomInt = rg.nextInt(1000);
System.out.println("Generated : " + randomInt);
}


From above Example nextInt(1000) generate random number from 0 to 1000 and display output in console.

Count Number of web Elements present in web page using selenium



1) count number of Button By using Class Name

<input id="ctrl1_btnADD" class="cart" type="submit" lang="LBLAART" flag="REMOVE" value="Acart" name="lstproduct" alt="ACart" title="Add to Cart">



List<WebElement> allElements = driver1.findElements(By.className("cart"));
System.out.println(allElements.size());



2) count number of link using xpath


<a id="HOME" href="http://arunrajvdm.blogspot.com/">
<span lang="HOME">Home</span>
</a>


List<WebElement> allElements1 = driver1.findElements(By.xpath("//a"));
System.out.println(allElements1.size());

Tuesday 13 May 2014

Five simple steps to can check your EPF account balance

Here are five simple steps to can check your EPF account balance.

Step 1: Keep your EPFO account number handy. It is mentioned on your salary slip.

Step 2: Click the link Check Your EPF balance on the EPFO website, http://www.epfindia.gov.in/.

Check your PF balance onlineCheck your PF balance online. Picture courtesy:moeycontrol
Step 3: Select the state where your PF office is situated.

Step 4: Select the appropriate EPFO regional office. Knowing this is no rocket science. Your PF number is an alpha-numeric number and the first two letters stand for regional office. For instance, if the your PF number is DL/12345/6789 then choose DL as regional office code.

Step 5: Fill the online form with your name (as it appears on salary slip), your mobile number and your PF number. In thefirst box, you need to key in seven digits. So, in the example cited above, the set of number has only 5 digits, 12345. Here you have to add 00 in the first two boxes. Next box, fill in the three digit establishment code or leave it blank if you don't have one. Finally, the account number 6789 in the last box, and click submit.

You will receive an SMS in less than five minutes with your EPFO account balance, if your records are updated with EPFO office. Or else it will show data not found. You may have to get in touch with your employer in that case, or wait a bit longer for your data to be updated.Keep in mind that the account balance is updated up to 31/3/2012

Capture Bitmap Method in QTP



Saves the Screen capture of the object and saved with file ectension .png or .bmp depending upon the specified file extension.

Its used for store the screen capture of the test objects in QTP.


Syntax:

object.CaptureBitmap filename [override existing]

Object -> test object
Capturebitmap -> methode name
file name -> specified the full path file name with in quotes for wher we can stored the image file.
Override Existing -> True or False
        True -> the file override, if the file name already exists
        false -> defaulty QTP set as false, its not override.
Return Value : NONE

Ex:

Browser("Gmail: Email from Google").Page("Gmail: Email from Google").WebButton("Sign in").CaptureBitmap "E:\signin.bmp",True




Store screen shot hyperlink in excel using CaptureBitmap Method


Example Script:

Browser("Browser").Page("Order Summary").CaptureBitmap TestPath&"\Screenshots\"&"Number Of Access = "&NoOfAccess&".bmp",true
Linklocation =  TestPath&"\Screenshots\"&"Number Of Access = "&NoOfAccess&".bmp"
WS.Cells(i,12).value="=HYPERLINK("&""""&Linklocation&""""&","&""""&"Number Of Access = "&NoOfAccess&""""&")"


Here,

Testpath = Computer location used for save the screen shot


The above script used to capture the screen shot and saved into the perticular location. And stored as hyperlink in Excel.



Browser("Browser").Page("Order Summary").CaptureBitmap TestPath&"\Screenshots\"&Testcase&".bmp",true
Linklocation =  TestPath&"\Screenshots\"&Testcase&".bmp"
WS.Cells(i,12).value="=HYPERLINK("&""""&Linklocation&""""&","&""""&Testcase&""""&")"

Synchronization in Selenium

Synchronization is machanism for working more than one component working parellel each other.

Generally in test Automation, we can deal with two components,

1) Application under test.
2) Test Automation Tool

The above both componenets are working in different speed. So we can write the script for such a way to maintain same speed for above two components. SO that we will not encounter "Elements not found" error.

Two type of Synchronization

1) Unconditional Synchronization
2) Conditional Synchronization



1) Unconditional Synchronization

-> Here we can mention only time out value.

-> Its tell to the tool waiting for some specify amount of time.

EX: Thread.Sleep(30000)

The tool waitining for 30 sec while using above code.

Advantage : If we want to interact with third party systems like interface, its not possible to check the condition or write the condition. Here in the situation, we tell to the tool waiting for some amount of time by specified timeout value.

Disadvantage : If we specify the timeout value for 30 sec, the tool should waiting 30 sec, eventhough the application ready for 20 sec. So here the executing waiting for 10 sec unnecessarily. This is one of disadvantage for using un-conditional synchronization.




2) Conditional Synchronization

-> We specify a condition along with timeout value, so that tool waits to check for the condition and then come out if nothing happens. If the condition satisfied before timout value, its come proceed next step. So that we can avoid the tool waiting for lone time unnecessarily.

-> we have two condition synchronization

i) implicit synchronization
ii) Explicit Synchronization


i) Implicit synchronization

The implicit statement is used to tell web driver for wait certian time to find the element.

a) Element implicit Synchronization

-> We can set the default element existance timeout. Below statement will set the default object synchronization timeout as 20. This means that selenium script will wait for maximum 20 seconds for element to exist.

->If Web element does not exist within 20 seconds, it will throw an exception.

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

-> This machanism which written once and applied for entire script for find element. Its should defined once initiate the web driver.

-> Implicit wait will not work all the commands/statements in the application. It will work only for "FindElement" and "FindElements" statements.

-> We should always remember to add the below syntax immediately below the Webdriver statement.


b) Page Load Synchronization

-> We can set the default page navigation timeout. Below statement will set the navigation timeout as 50. This means that selenium script will wait for maximum 50 seconds for page to load.

-> If page does not load within 50 seconds, it will throw an exception.

driver.manage().timeouts().pageLoadTimeout(50,TimeUnit.SECONDS);



ii) Explicit Synchronization

-> We need to define the wait statement for certian condition to be satisfied until specified time period. if the webdriver find the element then it will execute.

-> we need to import WebDriverWait class using this statement.


 WebDriverWait wait = new WebDriverWait(driver, 10);

 wait.ignoring(NoSuchElementException.class);

 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("statedropdown")));





Example code

WebDriverWait wait = new WebDriverWait(FireFoxDriver, 10);

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(“list-cnt”)));

visibilityOf(WebElement element) – An expectation for checking that an element, known to be present on the DOM of a page, is visible.

titleIs(java.lang.String title) – An expectation for checking the title of a page.

titleContains(java.lang.String title) - An expectation for checking that the title contains a case-sensitive substring

textToBePresentInElementValue(By locator, java.lang.String text) – An expectation for checking if the given text is present in the specified elements value attribute.

textToBePresentInElement(By locator, java.lang.String text) – An expectation for checking if the given text is present in the specified element.

stalenessOf(WebElement element) – Wait until an element is no longer attached to the DOM.

refreshed(ExpectedCondition<T> condition) – Wrapper for a condition, which allows for elements to update by redrawing.

presenceOfElementLocated(By locator) – An expectation for checking that an element is present on the DOM of a page.

presenceOfAllElementsLocatedBy(By locator) – An expectation for checking that there is at least one element present on a web page.

not(ExpectedCondition<?> condition) - An expectation with the logical opposite condition of the given condition.

invisibilityOfElementWithText(By locator, java.lang.String text) – An expectation for checking that an element with text is either invisible or not present on the DOM.

invisibilityOfElementLocated(By locator) – An expectation for checking that an element is either invisible or not present on the DOM.

frameToBeAvailableAndSwitchToIt(java.lang.String frameLocator) – An expectation for checking whether the given frame is available to switch to.

elementToBeSelected(WebElement element) – An expectation for checking if the given element is selected.

elementToBeSelected(By locator)

elementToBeClickable(By locator) – An expectation for checking an element is visible and enabled such that you can click it.


WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(“someid”)));






Fluent Wait:

Using FluentWait we can define the maximum amount of time to wait for a condition, as well as the frequency with which to check for the condition.

And also the user can configure to ignore specific types of exceptions such as "NoSuchElementExceptions" when searching for an element.

Syntax:



Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)

//Wait for the condition

      .withTimeout(30, TimeUnit.SECONDS)

        // which to check for the condition with interval of 5 seconds.

      .pollingEvery(5, TimeUnit.SECONDS)

    //Which will ignore the NoSuchElementException

      .ignoring(NoSuchElementException.class);

Thursday 8 May 2014

Working with excel using selenium web driver (using Apache POI)

Apache POI

For Download = http://poi.apache.org/download.html


-> Apache POI is a powerful Java library to work with different Microsoft Office file formats such as Excel, Power point, Visio, MS Word etc.

-> The name POI was originally an acronym for Poor Obfuscation Implementation, referring humorously to the fact that the file formats seemed to be deliberately obfuscated, but poorly, since they were successfully reverse-engineered.

-> Apache POI library v3.8 or above. And download .Jar file like this format poi-bin-3.10 .jar in this link = http://poi.apache.org/download.html

-> Make sure to include apache poi jar file to your project. If your project uses Maven as dependency management, add following in your Pom.xml file.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.8</version>
</dependency>
If you are not using Maven then you can directly add required JAR files in your classpath.





POI classes used for working with Excel

Apache POI main classes usually start with either HSSF, XSSF or SXSSF.

-> HSSF is the POI Project’s pure Java implementation of the Excel ’97(-2007) file format. e.g. HSSFWorkbook, HSSFSheet.

-> XSSF is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g. XSSFWorkbook, XSSFSheet.

-> SXSSF (since 3.8-beta3) is an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited. e.g. SXSSFWorkbook, SXSSFSheet. SXSSF achieves its low memory footprint by limiting access to the rows that are within a sliding window, while XSSF gives access to all rows in the document.

-> Apart from above classes, Row and Cell are used to interact with a particular row and a particular cell in excel sheet.

-> Another useful class FormulaEvaluator is used to evaluate the formula cells in excel sheet.

-> A wide range of classes like CellStyle, BuiltinFormats, ComparisonOperator, ConditionalFormattingRule, FontFormatting, IndexedColors, PatternFormatting, SheetConditionalFormatting etc. are used when you have to add formatting in a sheet, mostly based on some rules.





Similar to HSSF(Horrible SpreadSheet Format), POI has different prefix for other file formats too:

-> HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
-> XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
-> HPSF (Horrible Property Set Format) – reads “Document Summary” information from Microsoft Office files.
-> HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
-> HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
-> HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
-> HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
-> HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files
-> DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.


***********************************************

Reading an excel file

Reading an excel file is also very simple if we divide this in steps.

-> Create workbook instance from excel sheet
-> Get to the desired sheet
-> Increment row number
-> Iterate over all cells in a row
-> Repeat step 3 and 4 until all data is read



Code For Reading data from .xls file

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

FileInputStream file1=new FileInputStream(new File("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Login1.xls"));
HSSFWorkbook workbook1=new HSSFWorkbook(file1);
HSSFSheet worksheet1=workbook1.getSheetAt(1);
Iterator<Row> rowiterator1=worksheet1.iterator();
while(rowiterator1.hasNext())
{
Row row1=rowiterator1.next();
Iterator<Cell> celliterator1=row1.cellIterator();
while(celliterator1.hasNext())
{
Cell cell1=celliterator1.next();
int cellType = cell1.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue()+"\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue()+"\t");
break;
}
System.out.println("\n");
}
}
file1.close();


Note : 
1) Change the above code from "Switch" to "if-else" statement if we have error like "case expressions must be constant expressions".
2) In Eclipse IDe, we can change "Switch" to "if-else" by clik on switch and pressing "CTRL+1".


***************************************

Code For Reading data from .xlsx file

FileInputStream file1=new FileInputStream(new File("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\POI_Example.xlsx"));
XSSFWorkbook workbook1=new XSSFWorkbook(file1);
XSSFSheet worksheet1=workbook1.getSheetAt(0);
Iterator<Row> rowiterator1=worksheet1.iterator();
while(rowiterator1.hasNext())
{
Row row1=rowiterator1.next();
Iterator<Cell> celliterator1=row1.cellIterator();
while(celliterator1.hasNext())
{
Cell cell1=celliterator1.next();
int cellType = cell1.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue()+"\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue()+"\t");
break;
}
System.out.println("\n");
}
}
file1.close();


*************************************************************

How to write .xls file using apachi poi in selenium webdriver


We should use HSSFWorkbook and HSSFSheet class while working with .xls file.


package Model_Package;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ExcelOperation {


public static void main(String[] args) throws IOException,FileNotFoundException {

try{
Cell searchcell=null;
FileInputStream File1=new FileInputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");

HSSFWorkbook workbook1=new HSSFWorkbook(File1);
HSSFSheet Sheet1=workbook1.getSheetAt(0);   // Here "0" refers First WorkSheet. if "1" means its refer Seconds Sheet

Row row1=Sheet1.createRow(0);   //Here "0" indicates First Row.
searchcell=row1.createCell(0);  //Here "0" indicates first column of the specified row.

searchcell.setCellValue("Selenium");   //insert the "Selenium" text into that cell value
File1.close(); // close the input File Stream

FileOutputStream File2=new FileOutputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");
workbook1.write(File2);
File2.close();

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

}

}




i) How to get know last used row(End of the Text) in Excel Sheet

Integer Lastrow;
Lastrow = Sheet1.getLastRowNum();
Lastrow=Lastrow+1;



ii)  Issue while write Excel Sheet using Apache POI

We got Error while use below code to access the cell in Excel


 
  FileInputStream file = new FileInputStream(new File("C:\\testdata.xls"));  
  HSSFWorkbook workbook = new HSSFWorkbook(file);
 
  HSSFSheet sheet = workbook.getSheetAt(0);
   
  Cell searchText3 = sheet.getRow(0).getCell(0);
  searchText3.setCellValue("Test Search Keyword");
 
  file.close();
 
  FileOutputStream outFile =new FileOutputStream(new File("C:\\testdata.xls"));
  workbook.write(outFile);
  outFile.close();



The below Error while access the cell in Excel


Exception in thread "main" java.lang.NullPointerException at xltest.main(xltest.java:28)


Solution :

-> The below code is not working and return Null value.

 Cell searchText3 = sheet.getRow(0).getCell(0);

So we got the Null Pointer Exception while run the code.

-> Instead of above code we shoule use below code for access cell in Excel


Row row1=Sheet1.createRow(0);
searchcell=row1.createCell(0);







******************************************



How to write .xlsx file using apachi poi in selenium webdriver


We should use XSSFWorkbook and XSSFSheet class while working with .xlsx file.



package Model_Package;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ExcelOperation {


public static void main(String[] args) throws IOException,FileNotFoundException {

try{
Cell searchcell=null;
FileInputStream File1=new FileInputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");

XSSFWorkbook workbook1=new XSSFWorkbook(File1);
XSSFSheet Sheet1=workbook1.getSheetAt(0);  // Here "0" refers First WorkSheet. if "1" means its refer Seconds Sheet

Row row1=Sheet1.createRow(0);   //Here "0" indicates First Row.
searchcell=row1.createCell(0);  //Here "0" indicates first column of the specified row.

searchcell.setCellValue("Selenium");   //insert the "Selenium" text into that cell value
File1.close(); // close the input File Stream

FileOutputStream File2=new FileOutputStream("D:\\Selenium_Testing\\Selenium_Webdriver_Project\\Apache.xls");
workbook1.write(File2);
File2.close();

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

}

}





difference between iterator,Arraylist and list iterator in java


Arraylist :

-> ArrayList is an actual data structure, an implementation of the List interface
-> ArratList is actual list of the object content the value.
-> Its have the method like add(object), remove(object), get(index), etc.


1) boolean add(E e) - This method appends the specified element to the end of this list.

2) void add(int index, E element) - This method inserts the specified element at the specified position in this list.

3) boolean addAll(Collection<? extends E> c) - This method appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator

4) boolean addAll(int index, Collection<? extends E> c) - This method inserts all of the elements in the specified collection into this list, starting at the specified position.

5) void clear() - This method removes all of the elements from this list.

6) Object clone() - This method returns a shallow copy of this ArrayList instance.

7) boolean contains(Object o) - This method returns true if this list contains the specified element.

8) void ensureCapacity(int minCapacity) - This increases the capacity of this ArrayList.

9) E get(int index) - This method returns the element at the specified position in this list.

10) int indexOf(Object o) - This method returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

11) boolean isEmpty() - This method returns true if this list contains no elements.

12) int lastIndexOf(Object o) - This method returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

13) E remove(int index) - This method removes the element at the specified position in this list.

14) boolean remove(Object o) - This method removes the first occurrence of the specified element from this list, if it is present.

15) protected void removeRange(int fromIndex, int toIndex) - This method removes from this list all of the elements whose index is between fromIndex(inclusive) and toIndex(exclusive).

16) E set(int index, E element) - This method replaces the element at the specified position in this list with the specified element.

17) int size() - This method returns the number of elements in this list.

18) Object[] toArray() - This method returns an array containing all of the elements in this list in proper sequence (from first to last element).

19) <T> T[] toArray(T[] a) - This method returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that
of the specified array.

20) void trimToSize() - This method trims the capacity of this ArrayList instance to be the list's current size.




Iterator :

-> Iterator is just an interface that allows you to navigate through any data structure.
-> Iterator is helpful for navigate and access the data.
-> Iterator have the below method
-> Iterator is used for map, set, and list.

1) boolean hasNext( ) - Returns true if there are more elements. Otherwise, returns false.

2) Object next( ) - 1Returns the next element. Throws NoSuchElementException if there is not a next element.

3) void remove( ) - Removes the current element. Throws IllegalStateException if an attempt is made to call remove( ) that is not preceded by a call to next( ).



ListIterator:

-> ListIterator is a subclass which extends Iterator.
-> ListIterator allow bidirectional traversal of a list, and the modification of elements.
-> ListIterator is only used for lists, and not used for map, set, and list.


1) void add(Object obj) - Inserts obj into the list in front of the element that will be returned by the next call to next( ).

2) boolean hasNext( ) - Returns true if there is a next element. Otherwise, returns false.

3) boolean hasPrevious( ) - Returns true if there is a previous element. Otherwise, returns false.

4) Object next( ) - Returns the next element. A NoSuchElementException is thrown if there is not a next element.

5) int nextIndex( ) - Returns the index of the next element. If there is not a next element, returns the size of the list.

6) Object previous( ) - Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.

7) int previousIndex( ) - Returns the index of the previous element. If there is not a previous element, returns -1.

8) void remove( ) - Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked.

9) void set(Object obj) - Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

QTP Menu list is Empty after click Menu bar

Solution :

Right Click from near menu bar -> Customize -> Toolbars -> Restore all -> Restart QTP

From above step we can solve this problem.


QTP unable to find object in IE due to BHOManager CLASS add-on missing


This "BHOManager CLASS" add-on is a supporting add-on to run QTP script on the IE browser.

The publisher of this add-on is Mercury Interactive Corp.

I have uninstalled the existing IE browser because of some issues in my machine and reinstalled it. And after this i cannot run the QTP script as the "BHOmanager Class" add-on is missing.



http://stackoverflow.com/questions/13586606/how-to-install-the-bhomanager-class-add-on-in-ie


http://h30499.www3.hp.com/t5/Unified-Functional-Testing/HP-QTP-11-cant-recognise-IE8-browser-events-refresh-and-navigate/td-p/5317811#.U1YUTfmSyQ5




regsvr32 -u "C:\Windows\SysWOW64\BHOManager.dll
regsvr32 "C:\Windows\SysWOW64\BHOManager.dll




QTP is not recognise the object in Windows7 and IE8(64 bit)

1) Check the  BHOManager Add on in IE 8

Go to IE > Tools > Manage Add-ons, make sure BHOManager class
(Browser Helper Object) from Mercury Interative Corporation is
enabled.

Enabled BHOManager add on alone. And diabled rest of the Add on.

2) Please check if the iexplorer.exe of the AUT (Application Under Test) is 32 or 64 bit based, for it you can open the task manager, select the application nameà right click à go to process à and if the is an *32 next to the iexplorer.exe then the application is 32 bit based, otherwise is 64 bit.

Depending of it please use the following command thru the CMD to re-register the BHOmanager.dll, please close all browsers:

For the 32 bit:
                              regsvr32 -u "C:\Windows\System32\BHOManager.dll"
                              regsvr32 "C:\Windows\System32\BHOManager.dll"
For the 64 bit:


                              regsvr32 -u "C:\Windows\SysWOW64\BHOManager.dll"
                              regsvr32 "C:\Windows\SysWOW64\BHOManager.dll"



3) Check IE8 version is 32 bit or 64 bit, by using below method,

Method 1:

From Help-> About INternet Explorer ->  first line gives the version number. If it is 64 bit, it will say so. If 32 bit, it shows the version number only.Its doesnot show like 32 bit.


If your win7 is not have 64 bit IE8 means, you are using IE 32 bit versions alone.


If you are using a 64 bit Win7, both are listed in
Start -> All Programs.
Internet Explorer (64-bit)
Internet Explorer


Method 2:

We can check the IE location from Right click of the Properties from IE icon.


The 32 bit IE is located here:

C:\Program Files (x86)\Internet Explorer\iexplore.exe

The 64 bit IE is located here:

C:\Program Files\Internet Explorer\iexplore.exe


From above step, we get confirm IE is 32 bit or 64 bit edition.Then find the location for HP instalation path to know about which IE have the BHOmanager Add on

-> If QTP innstalled in below path

C:\Program Files (x86)\HP\QuickTest Professional

we come to conclusion IE with 32 bit have the BHOmanager Add on.


-> If QTP innstalled in below path

C:\Program Files\HP\QuickTest Professional

we come to conclusion IE with 64 bit have the BHOmanager Add on.

Difference between final,finally,finalize



Final:

-> Final is access modifier, its applicable for variable,method and class
-> IF variable is final - we can change the value.its constent
-> If method is final - The sub class cannot overwrite
-> If class is final - we can not extends this class. not able to create sub class.

Different between Access specifiers and Access modifiers




From C++:

Public,private,protected,default are Access specifier. But rest of the final, static,synchronized,abstract,native,strictfp,transiant,volatile are Access modifiers.

From Java

we dont have Access specifier terminalogy in java. All 12 Public,private,protected,default, final, static,synchronized,abstract,native,strictfn,transiant,volatile  are Access modifiers only.

The only Access modifiers allowed for top level classes are public,default,final,abstract,strictfp

Difference between Interface and Abstract class





1)if we dont know anything about  implementation, just we have only requirement specification. then we go for interface.

If we know the implmentation, but not fully. We know the partial implementation then we go for Abstract class.


2) By default All method in interface is public and abstract, even its not declared too.So interface itself 100% abstract class.

methods in abstract class may have abstract or concrete.


3) we cannot use follwing access modifiers in interface Private,protected,final,static,synchronized,native,strictfp. That means interface only allowed public and abstract.

But there is no restriction for using access modifiers in Abstract class.

4) All the methods in interface should override in subclass.

If sub class is not override interface means is called abstract class

Difference between Interface, Abstract class and Concrete class




1)if we dont know anything about  implementation, just we have only requirement specification. then we go for interface. Ex:Servlet

If we know the implmentation, but not fully. We know the partial implementation then we go for Abstract class. Ex: Generic Servlet and HttpServlet

If we know fully implamentation and ready to provide service then we can go for concrete class. Ex: MyOwnServlet class

Difference between overloading and overriding in JAVA



1) overloading - compiler decides which method should invoked .
overriding - JVM decides which method should invoked.

2) overloading - is called compile time polymorphism.
overriding - is called run time polymorphism.

3) Overloading - Arguments must change.
Overriding - Arguments should not change.

4) overloading - Return type can change.
overriding - Return type should not change.

5) overloading - Can throw new or broader exception.
overriding - should not throw any exception. but can throw runtime exception.

6) overloading - Reference type determine which method invoked during compile time.
overriding - object type decides which method invoked during run time.




Difference between instance variable,Referance Variable,Local variable in JAVA




Instance Variable - The variable which we can use with in class and also referring those values in outside class is called instance variable.

Reference variable - The variable which used to create object is called refernce variable.

local Variable - local Variable lifetime will end with in the braces.

Example :

class b{
pubic calc(int b,int c){
int d=b+c
System.out.println(d);
}

class main{
public static void main(String args[]){
b obj1=new b();
obj1.calc(4,5);
}

from above example

b and c = instance variable
c = local variable
obj1=reference variable


How to identify web elements using XPATH in Selenium Webdriver



1) //html tag[@attribute_Name = 'attribute Value']

Ex:  //input [@id='text']



2) Any Html Tag

Ex: *[@id='text']



3) Duplicate element

//descendent :: input[@id='text']



4) Using more than two element

//input[@id='text' and name='username']



5) Element contains value

//html tag[contains(@attribute_name,'attribute_value')]
//input [contains(@id,'xt')



6) Element Starts with value

//input[starts-with(@id,'te')]



7)identify the last element

//input[@id='text'][1]]
//input[@id='text'][2]]
//input[@id='text'][last()]



8) Eliminate (Truncate) header and tailor spaces

we should use correct text including space while use element value. but its diffcult to find the spaces for element value using firebug. so we can use NORMALIZE-SPACE for  Eliminate (Truncate) header and tailor spaces.

//*[normalize-space(@value)="click me"]  


*************************************************************************


How to work with XPATH in selenium webdriver


Below symbol used to write the Xpath


1) "/" used to Search the element in root node.

EX: driver.findelement(By.xpath("/html/body/form/div[3]/div/div/ul/li[3]/span[@id='red']"))

Search element from root (html).


2) "//" used to Search the element in whole document. selection no matter where they are

  EX:  driver.findelement("//li[3]/span[@id='red']")

Seacrh element from third occurence li (li[3]) in whole document at any where. its not search on specific location.


3) "." used to Selects the current node

4) ".." used to Selects the parent of the current node

5) "@"  Selects the attribute

   Ex: <li id="lstproducts_ctrl5_prodlistitm" flag="AddToCart">
<a id="DUP012" title="Take Two" href="ProductDetails_US/Take-training.aspx">
<input id="nADD" class="cart" type="submit" " value="Green" name="lst$ctrl5$btnADD" alt=" Cart" title=" Cart">
</li>


driver.findelement("//li[3]/input[@value='Green']")

Here "value" is the attribute inside the input element




consider below example


<html>
<body>
<form>
<li id="lstproducts_ctrl5_prodlistitm" flag="AddToCart">
<a id="DUP011" title="Take Two" href="ProductDetails_US/Take-training.aspx">
<input id="nADD" class="cart" type="submit" " value="Blue" name="lst$ctrl5$btnADD" alt=" Cart" title=" Cart">
</li>

<li id="lstproducts_ctrl5_prodlistitm" flag="AddToCart">
<a id="DUP012" title="Take Two" href="ProductDetails_US/Take-training.aspx">
<input id="nADD" class="cart" type="submit" " value="Green" name="lst$ctrl5$btnADD" alt=" Cart" title=" Cart">
</li>


<li id="lstproducts_ctrl5_prodlistitm" flag="AddToCart">
<a id="DUP013" title="Take Two" href="ProductDetails_US/Take-training.aspx">
<input id="nADD" class="cart" type="submit" " value="Red" name="lst$ctrl5$btnADD" alt=" Cart" title=" Cart">
</li>

</form>
</body>
</html>




o/p  (Buttons)


Blue  Green  Red




1) How to click button ("Blue") using xpath

-> driver.findelement(by.xpath("/html/body/form/li[1]/input[@value='Blue']")).click
-> driver.findelement(By.xpath("//input[@value='Blue']").click


2) How to click second Button ("Green") using xpath

-> driver.findelement(by.xpath("/html/body/form/li[2]/input[@value='Green']")).click
-> driver.findelement(By.xpath("//input[@value='Green']").click


3) How to click randomly any button at run time

List(WebElement) CountButton=driver.findelements(By.Xpath("//input[@class='cart']")

Random rg=new Random(CountButton);
Integer RandomNumber1=rg.nextInt(rg);

driver.findelement(By.xpath("//li["+RandomNumber1+"]/input[@class='cart']")).click();



********************************************************************************************************************************


How to verify Xpath statement in firebug?


1) Open firebug in firefox/Chrome.
2) Go to console.
3) type : $x("<xpath>").
4) Hit Enter.
5) If it is correct path you can element in that console. If you mouse hover on that, the element will highlight in web page.


Example:

type : $x("//input[@value='Green']") in console



Thursday 1 May 2014

Working with different browser using Selenium Web Driver

For firfox browser

We no need to set any system property for Firefox fox browser. we can use directly after download selenium.


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


public class Testing1 {

public static void main(String[] args) {

FirefoxDriver fd=new FirefoxDriver();
fd.get("http://google.com");
System.out.println(fd.getTitle());
fd.close();

}

}


***************************

For Chrome Browser

The above code alone is not work. we need to set system property as per in below step.

1)Download the chrome driver from selenium download.Then save in location "E:\chrome\ChromeDriver.exe"
2)And add the system property as
System.setProperty("Webdriver.chrome.driver",""E:\chrome\ChromeDriver.exe")

we can see the path "Webdriver.chrome.driver" in Error message if we are not download the ChromeDriver.exe file.


3) so below code is work for chrome browser

import org.openqa.selenium.Chrome.ChromeDriver;


public class Testing1 {

public static void main(String[] args) {
System.setProperty("Webdriver.chrome.driver",""E:\chrome\ChromeDriver.exe")

ChromeDriver fd=new ChromeDriver();
fd.get("http://google.com");
System.out.println(fd.getTitle());
fd.close();

}

}


*******************************************


For Internet Explorer Browser 8

we need to set system property as per in below step.

1)Download the IE driver from selenium download.Then save in location "E:\IE\InternetExplorerDriver.exe"

2)And add the system property as
System.setProperty("webdriver.ie.driver",""E:\IE\InternetExplorerDriver.exe")

we can see the path "webdriver.ie.driver" in Error message if we are not download the InternetExplorerDriver.exe file.


3) so below code is work for Internet Explorer

import org.openqa.selenium.ie.InternetExplorerDriver;


public class Testing1 {

public static void main(String[] args) {
System.setProperty("webdriver.ie.driver",""E:\IE\InternetExplorerDriver.exe")
InternetExplorerDriver fd=new InternetExplorerDriver();
fd.get("http://google.com");
System.out.println(fd.getTitle());
fd.close();

}

}

Static and Non Static in JAVA

Static and non-static

-> Static Variable have only one memory allocation and its accessed by all objects.

-> we no need to create object for this static variable. we can diecrtly assign the value for static variable using class name. and we can use that ny using object name

Ex:

Public class example
{
int a;
static string str;

Public static void funct()
{
System.out.printl("Arunraj");
}
}


Public class example2 {
Public static void main(String aargs[])
{
example.str="Selenium"
example.funct();
example obj= new example()
obj.a=10
System.out.println(obj.a)
System.out.println(obj.str)

example obj1= new example()
example.str="Selenium"
obj1.a=10
System.out.println(obj1.a)
System.out.println(obj1.str)

}