Tuesday, 20 November 2012

To generate screen shot

To capture screenshot just place the below code in your script sometimes you might be running your script and you wanted to look what went wrong in application so you can capture the screen shot so you get a clear idea what went wrong on other side of your application.

In the below program I made it a function so that use place it in reusable section and pass paramaters such as file name and driver. It creates a folder by name screenshots and saves the screen shots as file name specified and prints you the location.


Reusable function



public static Object screenshot(String filename,WebDriver driver)
     {

try {

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir")+"//screenshots//"+filename+".jpg"));
System.out.println("Output screenshot stored at "+Calendar.getInstance().getTime()+ " in the path-->  "+System.getProperty("user.dir")+"\\screenshots\\");
String path="Output screenshot stored at "+Calendar.getInstance().getTime()+ " in the path-->  "+System.getProperty("user.dir")+"\\screenshots\\";

return path;

}
catch (IOException e)
{

e.printStackTrace();
System.out.println(filename+"Screenshot Failed to capture screenshot refer above details");

}
  return null;
}



The below is non reusable code to capture screenshot.



public static Object screenshot()
{

try {

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C://"+"//screenshots//"+filename+".jpg"));
}
 catch (IOException e)
{

e.printStackTrace();

}



Generate Random Number

There might be a need we could like to generate some random number to pass as test data to application, I wondered i could write a function so that each time it generates some random number so that i can run these scripts multiple times without worrying about the test data and guess what we can even pass the range whether you need single digit or two or digit or etc.



The below program illustrates random number generation within limit specified(10000).





 public static String getID(){

  int n=351;
 double d=0;          
 String Random;          
   int num=1;  
   {                    
while(true)          
{   
    
int final_limit=10000; //Specifiy the maximum limit          
d=Math.random()*final_limit;          
 num=(int)d;          
Random=String.valueOf(num);          
break;          
         
}
         
return Random;  

//This will return random number every time you run within 10000(specified limit)     
}   
    
}          


       

How to read values from Excel in Selenium Webdriver

One of the most aspect and beneficial of any automation tool is how well it can support parameterization. When one means parametization it is how effectively it can read and write values from excel. The below program illustrates an example to read values from excel, before executing the program we need to add jxl jars to java build path.


Download jars from here    jxl jars


package exchange.skills.com;

import java.io.File;
import java.io.IOException;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class Data_driven {
public String[][] getXLData(String location, String sheetname)
    {
            Workbook w = null;
            try {
                    w = Workbook.getWorkbook(new File(location));
            } catch (BiffException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            }
            Sheet s = w.getSheet(sheetname);
            String a[][] = new String[10][10];
            try
            {
            for (int j=0;j<s.getColumns();j++)
            {
                    for (int i=0;i<s.getRows();i++)
                    {
                            a[j][i] = s.getCell(j, i).getContents();
                            System.out.println(j+" and "+i+" "+a[j][i]);//Prints cell content one by one
                    }
            }


            }
            catch(Exception e)
            {
                    e.printStackTrace();
            }
            return a;
 
}
public static void main(String[] args) {
Data_driven n= new Data_driven();
//n.getXLData("location of excel file stored","sheet name")
n.getXLData("C:\\tc.xls", "sheet");//File where excel is placed-specify 2007 or save as excel workbook
}
}

Handling Dynamic Object using Action Builder class

The below script illustrates the use of action builder class to work on hidden object.


There is no direct approach to work on hidden objects using selenium webdriver, when i mean hidden objects sometimes we drag our mouse over something and we get to see some list which is clickable, these list are not popped up if we click on those links only dragging a mouse over that link will actually display the contents. To work with such kind we need to action builder class.
What Action builder class does? It actually controls mouse movement, first it will go that particular link and trigger mouse left button and without releasing the left button will go that particular content which needs to be clicked.

I have taken example of Flipkart.com where we get to see the various categories of items when we drag our mouse over the categories links.




package com.flipkart;

import java.io.File;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;

public class flipkart {

void click()
{

File file = new File("C:/IE driver/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver d = new InternetExplorerDriver();
d.get("http://www.flipkart.com");
WebElement M = d.findElement(By.xpath(".//*[@id='fk-header-tab-book']/div[1]/a/div/div// maa[1]/div"));//Main menu
WebElement SM=d.findElement(By.xpath(".//*[@id='fk-header-tab-book']/div[2]/div[1]/div/div/ul[1]/li[1]/a"));//hidden dynamic element




Actions builder = new Actions(d);// To hold mouse on menu
 builder.moveToElement(M).build().perform();
 SM.click();
}
public static void main(String[] args) {
flipkart l= new flipkart();
l.click();//Calling the method

}

}

Wednesday, 17 October 2012

XSLT REPORTS

What is XSLT reports?

XSLT stands for Extensible Style sheet Language Transformations. TestNG has default built in html reports which acutally presents a UI report of test scripts but if there is a urge to generate reports with graphical presentation more attractive UI then we can go for xslt reports. XSLT reports are basically more styling done for html which will generate graphical result of test scripts that's been executed.





To get xslt reports

        Go to project (Eclipse) and create new package(xslt)
        Create a new file with “ .xsl extension”.
(Or)
        Paste the testng-results.xsl  in the xslt package
        Add line to bat file after run as follows
“ant makexsltreports”
        Now go to project ->test-output->index.html.




ANT


How to run tests using ANT




                  Go to http://ant.apache.org/bindownload.cgi

    Click on zip file below the Current Release of Ant title.

      Unzip to a folder the downloaded zip file(ant)

         Go to My Computer-Properties(Right click My Computer)

        Now go to Advanced system settings

        Click on Environment variables then

Step 1



        Click on New below system variables(creating new environment variables)
        Enter "ANT_HOME" in variable name field
        Enter the path(the extracted folder of ant) of ant in variable value field

Eg:  "C:\\ant\apache-ant-1.8.4"(path)




Step 2



        Scroll down in system variable and find path in variable column
        Select path and click on edit
        Now go to variable value, go to end and type ";"(semicolon)
        Paste the path of the ant("C:\\ant\apache-ant-1.8.4") and add "\bin"

Eg:


 variable value= C:\Program Files\PC Connectivity Solution\;C:\Program Files\Java\jdk1.6.0_26\bin;C:\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin;C:\Program Files\QuickTime\QTSystem\;C:\\ant\apache-ant-1.8.4\bin

        Now click ok.


This completes configuring ant in your system.



To verify whether ant is configured



        Go to cmd prompt and type ant.



Note:



If u get any error message "Unable to locate tools.jar" then

        Go to program files where java is installed
        Now  go to jdk-lib folder
        Copy tools.jar
        Paste it in jre-lib folder
        Now run ant in cmd prompt.


Note:



Next if u get error message" Build.xml file doesn't exist" then

->     Place your build.xml file directly in your project(not in source)




TestNG in Eclipse



Advantage of TestNG



        After running the test in Testng, click refresh on the project

        There is folder appearing "test output"

        Expanding "test output" folder we can see "index.html"

        Go to physical location of index.html

        Open index.html in any browser.


TestNG in Eclipse



To Install Testng in Eclipse




        Go to help menu-Install New Software in Eclipse.

        Paste below url respective of the eclipse version(Refer the link if you have any doubt "http://testng.org/doc/download.html") in the Work with field.


         For Eclipse 3.4 and above, enter http://beust.com/eclipse.
         For Eclipse 3.3 and below, enter http://beust.com/eclipse1.


        After entering the url you will get the option of "Testng"
        Select it (i.e Testng) and click next, this should install Testng in your eclipse.
        Ignore error if you face during the process.




To verify whether TestNG is installed in your system.



        Go to window-Show view-Other.
        Expand the Java folder(Show view window).
        There will be a option displayed as Testng.







Selenium Beginners

Selenium 


Selenium is a free source from thought works. It  has fast growing automation tool. In today's market folks are going towards this automation tool and has grabbed interest of lot of companies. This tool needs the knowledge of any programming language most people go with Java. So in short any developer can easily use this tool with little exploring to selenium concepts.

How to use Selenium?


There is nothing installing selenium, its just configuring selenium. Here I am precise on Java language and will focus on using selenium through eclipse.
To configure selenium - just add selenium jars(Webdriver) to java build path.
Selenium jars can be downloaded free of cost from http://seleniumhq.org/download/ and these jars updated regularly.