Sunday, December 15, 2013

Selenium Web driver Concepts

JUnit 4 Tutorial 1 – Basic Usage

Import org.junit.*;
import static org.junit.Assert.*;
import java.util.*;
 public class JunitTest1 { 
    private Collection collection;
     @BeforeClass
    public static void oneTimeSetUp() {
        // one-time initialization code  
     System.out.println("@BeforeClass - oneTimeSetUp");
    } 
    @AfterClass
    public static void oneTimeTearDown() {
        // one-time cleanup code
     System.out.println("@AfterClass - oneTimeTearDown");
    } 
    @Before
    public void setUp() {
        collection = new ArrayList();
        System.out.println("@Before - setUp");
    } 
    @After
    public void tearDown() {
        collection.clear();
        System.out.println("@After - tearDown");
    } 
    @Test
    public void testEmptyCollection() {
        assertTrue(collection.isEmpty());
        System.out.println("@Test - testEmptyCollection");
    } 
    @Test
    public void testOneItemCollection() {
        collection.add("itemA");
        assertEquals(1, collection.size());
        System.out.println("@Test - testOneItemCollection");
    }
}
Result :

@BeforeClass - oneTimeSetUp
@Before - setUp
@Test - testEmptyCollection
@After - tearDown
@Before - setUp
@Test - testOneItemCollection
@After - tearDown
@AfterClass - oneTimeTearDown

In JUnit 4, you have to declare “@BeforeClass” and “@AfterClass” method as static method.
JUnit 4 Tutorial 2 – Expected Exception Test




import org.junit.*;

public class JunitTest2 {

 @Test(expected = ArithmeticException.class) 
 public void divisionWithException() { 
   int i = 1/0;
 } 

}

In above example, the divisionWithException() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass.


JUnit 4 Tutorial 3 – Ignore Test




import org.junit.*; 
public class JunitTest3 { 
 @Ignore("Not Ready to Run") 
 @Test
 public void divisionWithException() { 
   System.out.println("Method is not ready yet");
 }  
}
In above example, JUnit will not test the divisionWithException() method.



JUnit 4 Tutorial 4 – Time Test


import org.junit.*; 
/**
 * JUnit TimeOut Test
 * @author mkyong
 *
 */
public class JunitTest4 { 
 @Test(timeout = 1000) 
 public void infinity() { 
  while (true); 
 } 
}

In above example, the infinity() method will not return, so the JUnit engine will mark it as failed and throw an exception


JUnit 4 Tutorial 5 – Suite Test


The “Suite Test” means bundle a few unit test cases and run it together. In Junit, both @RunWith and @Suite annotation are used to run the suite test.

The below example means both unit test JunitTest1 and JunitTest2 will run together after JunitTest5 is executed.


import org.junit.runner.RunWith;
import org.junit.runners.Suite; 
@RunWith(Suite.class)
@Suite.SuiteClasses({
        JunitTest1.class,
        JunitTest2.class
})
public class JunitTest5 {
}
Result :

@BeforeClass - oneTimeSetUp
@Before - setUp
@Test - testEmptyCollection
@After - tearDown
@Before - setUp
@Test - testOneItemCollection
@After - tearDown
@AfterClass - oneTimeTearDown


JUnit 4 Tutorial 6 – Parameterized Test




The “Parameterized Test” means vary parameter value for unit test. In JUnit, both @RunWith and @Parameter annotation are use to provide parameter value for unit test, @Parameters have to return List[], and the parameter will pass into class constructor as argument.




import java.util.Arrays;
import java.util.Collection; 
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
 @RunWith(value = Parameterized.class)
public class JunitTest6 { 
  private int number; 
  public JunitTest6(int number) {
     this.number = number;
  } 
  @Parameters
  public static Collection<Object[]> data() {
    Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };
    return Arrays.asList(data);
  }

  @Test
  public void pushTest() {
    System.out.println("Parameterized Number is : " + number);
  } 
}

Result :
Parameterized Number is : 1
Parameterized Number is : 2
Parameterized Number is : 3
Parameterized Number is : 4


List of Scenarios


1. Create a ArrayList ->Add Element -> Read Element
2. Create HashMap -> Add Element -> Read Element    Tip: HashMap has Key/Value pairs
3. Read and Write from Text File.
Tip : You will be using these Classes for doing the same: File, FileWriter, BufferedWriter, FileReader, BufferedReader 
4. JUNIT : Create simple test case ( may be launching google.com only) through JUNIT @Test annotation

Tip : You need to download JUNIT jar or configure in Eclipse. Public static main should not used for testfile class

5. Firefox Profile : Create Firefox profile manually and write Java Program to use that profile instead of default webdriver profile
6. Handling Javascript enabled message : Create Java Program to handle message popping up for enabling javascript.  Tip : You have use DesiredCapabilities Class to do the same
7. Identifying WebElement on Webpage : Use Class,id,name or any other attribute available to identify same element. You may use Absolute or Relative path. You may use gmail.com username website.
8. Extracting Links : Extract all links (name and url ) from bbc.com Tip : You will have to use findelements and tagname
9. Check Links  : Click all links on bbc.com and make sure they working. Tip : Check title after every click of like and make sure it does not contain 500 error.
10.Dropdown : Visit Timesofindia.com and change City drop down . Tip : Use Select class
11.RadioButton : Visit below URL and select checkboxes. Make sure you use findelements to get group of radioButton and then select rather than selecting individually.
http://www.echoecho.com/htmlforms10.htm
12. Screenshot : Write program to take screenshot of the page in test case.
13.Implicitwait :  Use implicit wait in testcase . Tip : Visit gmail.com -> Change definition of object to wrong value and make sure NoSuchElement exeption is thrown after 30 seconds.
14.New Tab/New Window/Pop Ups  : Visit hdfcbank.com and click Credit Card/Personal Account on write side. Do something on new window opened on click Credit Cards/Personal Account.
15. Certificate Error : Create Program to handle Certificate Error/acceptance page. Tip : Google and find out the code. The code should run.
16 . WebTable/Frames :  Visit espncricinfo.com and visit any fill scoreboard for a match and try to create a test case which adds individual batsman score and then compare this total  to total displayed on the scoreboard.
17.Javascript Error : Visit rediif.com -> Click Signin -> Click Ok without giving username/password - > Accept the error alert.

JUnit 4 Vs TestNG

JUnit 4 and TestNG are both very popular unit test framework in Java. Both frameworks look very similar in functionality. Which one is better? Which unit test framework should i use in Java project?
Here i did a feature comparison between JUnit 4 and TestNG.

junit-vs-testngjpg

1. Annotation Support

The annotation supports are implemented in both JUnit 4 and TestNG look similar.
Feature
JUnit 4
TestNG
test annotation
@Test
@Test
run before all tests in this suite have run
@BeforeSuite
run after all tests in this suite have run
@AfterSuite
run before the test
@BeforeTest
run after the test
@AfterTest
run before the first test method that belongs to any of these groups is invoked
@BeforeGroups
run after the last test method that belongs to any of these groups is invoked
@AfterGroups
run before the first test method in the current class is invoked
@BeforeClass
@BeforeClass
run after all the test methods in the current class have been run
@AfterClass
@AfterClass
run before each test method
@Before
@BeforeMethod
run after each test method
@After
@AfterMethod
ignore test
@ignore
@Test(enbale=false)
expected exception
@Test(expected = ArithmeticException.class)
@Test(expectedExceptions = ArithmeticException.class)
timeout
@Test(timeout = 1000)
@Test(timeout = 1000)

The main annotation differences between JUnit4 and TestNG are
1. In JUnit 4, we have to declare “@BeforeClass” and “@AfterClass” method as static method. TestNG is more flexible in method declaration, it does not have this constraints.
2. 3 additional setUp/tearDown level: suite and group (@Before/AfterSuite, @Before/AfterTest, @Before/AfterGroup). See more detail here.
JUnit 4
    @BeforeClass
    public static void oneTimeSetUp() {
        // one-time initialization code   
     System.out.println("@BeforeClass - oneTimeSetUp");
    }
TestNG
    @BeforeClass
    public void oneTimeSetUp() {
        // one-time initialization code   
     System.out.println("@BeforeClass - oneTimeSetUp");
}
In JUnit 4, the annotation naming convention is a bit confusing, e.g “Before”, “After” and “Expected”, we do not really understand what is “Before” and “After” do, and what we “Expected” from test method? TestNG is easier to understand, it using “BeforeMethod”, “AfterMethod” and “ExpectedException” instead.


3


Scenario : Consider a Test Case which requires you to login into a website like gmail.com , with different User Id and Passwords. User Id and Passwords are stored in Excel in below format. Sheet has third column for Run Mode also.

Solution :  We will use @DataProvider annotation available in TestNG to handle above scenario.
How :  @DataProvider annotation method will access data from excel and pass the same in the form of HashTable/Data Object to the test method.

testdata.xlsx ( It has sheet with name "TestData")

Username  | Password  | RunMode
hsingh       | password1 | Y
psingh       | password2 | Y
msingh      | password3 |Y


=========================================================================

package rough;
import java.util.Hashtable;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.qtpselenium.hybrid.util.Xls_Reader;

public class xldataprovider {

@Test(dataProvider="xldata")   
public void tescase(Hashtable<String,String> data){
   
    System.out.println(data.get("Username"));
    System.out.println(data.get("Password"));
      
}
 
@DataProvider
public Object[][] xldata(){
   
    Object[][] data=null;
    Xls_Reader xls= new Xls_Reader("C://Users//har//Documents//Eclipseworkspace//hybridframework//src//rough//testdata.xlsx");
   
    Hashtable<String,String> table =null;
    //Find number of columns in xls
   
    int numofcols=0;
    while(!xls.getCellData("TestData", numofcols, 1).equals("")){
       
        numofcols++;
       
    }
   
    System.out.println("Number of Columns are : " + numofcols) ;
   
    //Find number of rows in xls
   
    int numofrows=0;
    while(!xls.getCellData("TestData", 0, numofrows+2).equals("")){      //numofrow+2 is given as we need to start from 2nd row.First row is column Heading
       
    //    System.out.println(xls.getCellData("TestData", 0, numofrows)); 
        numofrows++;
       
    }
   
       
    System.out.println("Number of rows are : " + numofrows) ;
   
    // initialising data object with number of rows and one column.The data of one row will be put in one column of Hashtable
   
    data= new Object[numofrows][1];    //The column will be 1 only as we will put data in hash table.
       
    // Putting data in data Object
          
    for(int row=2;row<numofrows+2;row++ ){
        table=new Hashtable<String,String>();
        for(int col=0;col<numofcols;col++){
           
            table.put(xls.getCellData("TestData", col, 1),xls.getCellData("TestData", col, row) );
           
        }
       
        data[row-2][0]= table;
       
    }
   
   
    return data;
}

}

 ------------------------------------------------------------------------------------------
 
testdata.xlsx  ( It has sheet with name "TestData")

 Username | Password | RunMode
  hsingh     | password1| Y
  psingh     | password2 | Y
  msingh    | password3| Y

dataprovider ( will always be 1 column)

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEguBVeYczeArDdTly4fabFTkjWNxDwD1Y3BQeIl7hOK_t3oddOt6DDXyAwd4RbjV3RKRkmPoxER2WOuNobSWOzRXg3ibyj9nGLXo7wMk4Oo9_Joeg7DaMCiBCqML1R_z0YxpUeO4GDqbgM/s640/hash.png
















Xls_Reader Class

package com.qtpselenium.hybrid.util;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class Xls_Reader {
    public static String filename = System.getProperty("user.dir")+"\\src\\config\\testcases\\TestData.xlsx";
    public  String path;
    public  FileInputStream fis = null;
    public  FileOutputStream fileOut =null;
    private XSSFWorkbook workbook = null;
    private XSSFSheet sheet = null;
    private XSSFRow row   =null;
    private XSSFCell cell = null;
   
    public Xls_Reader(String path) {
       
        this.path=path;
        try {
            fis = new FileInputStream(path);
            workbook = new XSSFWorkbook(fis);
            sheet = workbook.getSheetAt(0);
            fis.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
    // returns the row count in a sheet
    public int getRowCount(String sheetName){
        int index = workbook.getSheetIndex(sheetName);
        if(index==-1)
            return 0;
        else{
        sheet = workbook.getSheetAt(index);
        int number=sheet.getLastRowNum()+1;
        return number;
        }
       
    }
   
    // returns the data from a cell
    public String getCellData(String sheetName,String colName,int rowNum){
        try{
            if(rowNum <=0)
                return "";
       
        int index = workbook.getSheetIndex(sheetName);
        int col_Num=-1;
        if(index==-1)
            return "";
       
        sheet = workbook.getSheetAt(index);
        row=sheet.getRow(0);
        for(int i=0;i<row.getLastCellNum();i++){
            //System.out.println(row.getCell(i).getStringCellValue().trim());
            if(row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
                col_Num=i;
        }
        if(col_Num==-1)
            return "";
       
        sheet = workbook.getSheetAt(index);
        row = sheet.getRow(rowNum-1);
        if(row==null)
            return "";
        cell = row.getCell(col_Num);
       
        if(cell==null)
            return "";
        //System.out.println(cell.getCellType());
        if(cell.getCellType()==Cell.CELL_TYPE_STRING)
              return cell.getStringCellValue();
        else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){
             
              String cellText  = String.valueOf(cell.getNumericCellValue());
              if (HSSFDateUtil.isCellDateFormatted(cell)) {
                   // format in form of M/D/YY
                  double d = cell.getNumericCellValue();

                  Calendar cal =Calendar.getInstance();
                  cal.setTime(HSSFDateUtil.getJavaDate(d));
                    cellText =
                     (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
                   cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" +
                              cal.get(Calendar.MONTH)+1 + "/" +
                              cellText;
                  
                   //System.out.println(cellText);

                 }

             
             
              return cellText;
          }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
              return "";
          else
              return String.valueOf(cell.getBooleanCellValue());
       
        }
        catch(Exception e){
           
            e.printStackTrace();
            return "row "+rowNum+" or column "+colName +" does not exist in xls";
        }
    }
   
    // returns the data from a cell
    public String getCellData(String sheetName,int colNum,int rowNum){
        try{
            if(rowNum <=0)
                return "";
       
        int index = workbook.getSheetIndex(sheetName);

        if(index==-1)
            return "";
       
   
        sheet = workbook.getSheetAt(index);
        row = sheet.getRow(rowNum-1);
        if(row==null)
            return "";
        cell = row.getCell(colNum);
        if(cell==null)
            return "";
       
      if(cell.getCellType()==Cell.CELL_TYPE_STRING)
          return cell.getStringCellValue();
      else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC || cell.getCellType()==Cell.CELL_TYPE_FORMULA ){
         
          String cellText  = String.valueOf(cell.getNumericCellValue());
          if (HSSFDateUtil.isCellDateFormatted(cell)) {
               // format in form of M/D/YY
              double d = cell.getNumericCellValue();

              Calendar cal =Calendar.getInstance();
              cal.setTime(HSSFDateUtil.getJavaDate(d));
                cellText =
                 (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
               cellText = cal.get(Calendar.MONTH)+1 + "/" +
                          cal.get(Calendar.DAY_OF_MONTH) + "/" +
                          cellText;
              
              // System.out.println(cellText);

             }

         
         
          return cellText;
      }else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
          return "";
      else
          return String.valueOf(cell.getBooleanCellValue());
        }
        catch(Exception e){
           
            e.printStackTrace();
            return "row "+rowNum+" or column "+colNum +" does not exist  in xls";
        }
    }
   
    // returns true if data is set successfully else false
    public boolean setCellData(String sheetName,String colName,int rowNum, String data){
        try{
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);

        if(rowNum<=0)
            return false;
       
        int index = workbook.getSheetIndex(sheetName);
        int colNum=-1;
        if(index==-1)
            return false;
       
       
        sheet = workbook.getSheetAt(index);
       

        row=sheet.getRow(0);
        for(int i=0;i<row.getLastCellNum();i++){
            //System.out.println(row.getCell(i).getStringCellValue().trim());
            if(row.getCell(i).getStringCellValue().trim().equals(colName))
                colNum=i;
        }
        if(colNum==-1)
            return false;

        sheet.autoSizeColumn(colNum);
        row = sheet.getRow(rowNum-1);
        if (row == null)
            row = sheet.createRow(rowNum-1);
       
        cell = row.getCell(colNum);   
        if (cell == null)
            cell = row.createCell(colNum);

        // cell style
        //CellStyle cs = workbook.createCellStyle();
        //cs.setWrapText(true);
        //cell.setCellStyle(cs);
        cell.setCellValue(data);

        fileOut = new FileOutputStream(path);

        workbook.write(fileOut);

        fileOut.close();   

        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
   
   
    // returns true if data is set successfully else false
    public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
        //System.out.println("setCellData setCellData******************");
        try{
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);

        if(rowNum<=0)
            return false;
       
        int index = workbook.getSheetIndex(sheetName);
        int colNum=-1;
        if(index==-1)
            return false;
       
       
        sheet = workbook.getSheetAt(index);
        //System.out.println("A");
        row=sheet.getRow(0);
        for(int i=0;i<row.getLastCellNum();i++){
            //System.out.println(row.getCell(i).getStringCellValue().trim());
            if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
                colNum=i;
        }
       
        if(colNum==-1)
            return false;
        sheet.autoSizeColumn(colNum); //ashish
        row = sheet.getRow(rowNum-1);
        if (row == null)
            row = sheet.createRow(rowNum-1);
       
        cell = row.getCell(colNum);   
        if (cell == null)
            cell = row.createCell(colNum);
           
        cell.setCellValue(data);
        XSSFCreationHelper createHelper = workbook.getCreationHelper();

        //cell style for hyperlinks
        //by default hypelrinks are blue and underlined
        CellStyle hlink_style = workbook.createCellStyle();
        XSSFFont hlink_font = workbook.createFont();
        hlink_font.setUnderline(XSSFFont.U_SINGLE);
        hlink_font.setColor(IndexedColors.BLUE.getIndex());
        hlink_style.setFont(hlink_font);
        //hlink_style.setWrapText(true);

        XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
        link.setAddress(url);
        cell.setHyperlink(link);
        cell.setCellStyle(hlink_style);
         
        fileOut = new FileOutputStream(path);
        workbook.write(fileOut);

        fileOut.close();   

        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
   
   
   
    // returns true if sheet is created successfully else false
    public boolean addSheet(String  sheetname){       
       
        FileOutputStream fileOut;
        try {
             workbook.createSheet(sheetname);   
             fileOut = new FileOutputStream(path);
             workbook.write(fileOut);
             fileOut.close();           
        } catch (Exception e) {           
            e.printStackTrace();
            return false;
        }
        return true;
    }
   
    // returns true if sheet is removed successfully else false if sheet does not exist
    public boolean removeSheet(String sheetName){       
        int index = workbook.getSheetIndex(sheetName);
        if(index==-1)
            return false;
       
        FileOutputStream fileOut;
        try {
            workbook.removeSheetAt(index);
            fileOut = new FileOutputStream(path);
            workbook.write(fileOut);
            fileOut.close();           
        } catch (Exception e) {           
            e.printStackTrace();
            return false;
        }
        return true;
    }
    // returns true if column is created successfully
    public boolean addColumn(String sheetName,String colName){
        //System.out.println("**************addColumn*********************");
       
        try{               
            fis = new FileInputStream(path);
            workbook = new XSSFWorkbook(fis);
            int index = workbook.getSheetIndex(sheetName);
            if(index==-1)
                return false;
           
        XSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
       
        sheet=workbook.getSheetAt(index);
       
        row = sheet.getRow(0);
        if (row == null)
            row = sheet.createRow(0);
       
        //cell = row.getCell();   
        //if (cell == null)
        //System.out.println(row.getLastCellNum());
        if(row.getLastCellNum() == -1)
            cell = row.createCell(0);
        else
            cell = row.createCell(row.getLastCellNum());
           
            cell.setCellValue(colName);
            cell.setCellStyle(style);
           
            fileOut = new FileOutputStream(path);
            workbook.write(fileOut);
            fileOut.close();           

        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
       
        return true;
       
       
    }
    // removes a column and all the contents
    public boolean removeColumn(String sheetName, int colNum) {
        try{
        if(!isSheetExist(sheetName))
            return false;
        fis = new FileInputStream(path);
        workbook = new XSSFWorkbook(fis);
        sheet=workbook.getSheet(sheetName);
        XSSFCellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
        XSSFCreationHelper createHelper = workbook.getCreationHelper();
        style.setFillPattern(HSSFCellStyle.NO_FILL);
       
       
   
        for(int i =0;i<getRowCount(sheetName);i++){
            row=sheet.getRow(i);   
            if(row!=null){
                cell=row.getCell(colNum);
                if(cell!=null){
                    cell.setCellStyle(style);
                    row.removeCell(cell);
                }
            }
        }
        fileOut = new FileOutputStream(path);
        workbook.write(fileOut);
        fileOut.close();
        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
       
    }
  // find whether sheets exists   
    public boolean isSheetExist(String sheetName){
        int index = workbook.getSheetIndex(sheetName);
        if(index==-1){
            index=workbook.getSheetIndex(sheetName.toUpperCase());
                if(index==-1)
                    return false;
                else
                    return true;
        }
        else
            return true;
    }
   
    // returns number of columns in a sheet   
    public int getColumnCount(String sheetName){
        // check if sheet exists
        if(!isSheetExist(sheetName))
         return -1;
       
        sheet = workbook.getSheet(sheetName);
        row = sheet.getRow(0);
       
        if(row==null)
            return -1;
       
        return row.getLastCellNum();
       
       
       
    }
    //String sheetName, String testCaseName,String keyword ,String URL,String message
    public boolean addHyperLink(String sheetName,String screenShotColName,String testCaseName,int index,String url,String message){
        //System.out.println("ADDING addHyperLink******************");
       
        url=url.replace('\\', '/');
        if(!isSheetExist(sheetName))
             return false;
       
        sheet = workbook.getSheet(sheetName);
       
        for(int i=2;i<=getRowCount(sheetName);i++){
            if(getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)){
                //System.out.println("**caught "+(i+index));
                setCellData(sheetName, screenShotColName, i+index, message,url);
                break;
            }
        }


        return true;
    }
    public int getCellRowNum(String sheetName,String colName,String cellValue){
       
        for(int i=2;i<=getRowCount(sheetName);i++){
            if(getCellData(sheetName,colName , i).equalsIgnoreCase(cellValue)){
                return i;
            }
        }
        return -1;
       
    }
       
    // to run this on stand alone
    public static void main(String arg[]) throws IOException{
       
        //System.out.println(filename);
        Xls_Reader datatable = null;
       

             datatable = new Xls_Reader("H:\\Student_Selenium_Workspaces\\Framework_Weekend\\src\\Framework_XL_Files\\Controller.xlsx");
                for(int col=0 ;col< datatable.getColumnCount("TC5"); col++){
                    System.out.println(datatable.getCellData("TC5", col, 1));
                }
    }
   
   
}



package test;

import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;



public class dataprovider {

   
    
@Test(dataProvider="testdata")
    public void testRegister(String username,String password){
               
        System.out.println(username + password);
       
       
    }
   
   
   
 @DataProvider
    public Object[][] testdata(){
       
      
  //number of rows reperesents number of times test has to be repeated
        //number of rows is in our case is 2 , so test will be repeated 2 times
        //number of columns is number of parameter in data. We have 2 as username and password

        
Object[][] data = new Object[2][2];
       
        //first row
        data[0][0]= "hm_singh2002@yahoo.com";
        data[0][1]="password1";
       
       
        //second row
        data[1][0]= "hmsingh@gmail.com";
        data[1][1]="password1";
           
           
       
        return data;
       
       
    }
   
}




Scenario : During the running of test case user wants some information to be logged in the console. Information could be any detail about present activity being performed by the test case step.

Solution : log4j jar api helps you to get the above scenario implemented in the running of Test Case.

How : Follow below steps : 

1) Include log4j jar in build path

2) Create log4j.properties in the package with below details


#Application Logs
log4j.logger.devpinoyLogger=DEBUG, dest1
log4j.appender.dest1=org.apache.log4j.RollingFileAppender
log4j.appender.dest1.maxFileSize=5000KB
log4j.appender.dest1.maxBackupIndex=3
log4j.appender.dest1.layout=org.apache.log4j.PatternLayout
log4j.appender.dest1.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n
log4j.appender.dest1.File=C:\\testing\\Application.log
#do not append the old file. Create a new log file everytime
log4j.appender.dest1.Append=false


3) Now do logging from any test case by using code like below

import org.apache.log4j.Logger;
public class Logging_Example {
    /**
     * @param args
     */
    public static void main(String[] args) {

        // add log4j.jar
        // add log4j.propertie directly inside the src folder
        // create the object in the code
       
       
 Logger APPLICATION_LOGS = Logger.getLogger("devpinoyLogger");
        APPLICATION_LOGS.debug("hello");
        APPLICATION_LOGS.debug("We are wrinting in to a log file");
        APPLICATION_LOGS.debug("starting the test case xyz test");
            
    }
}
1) Automation Feasibility Study

·          AUT automation fasibilty
·         Test Case automation feasibilty
·         Tool feasibility
2) Test Strategy

·          Design about Automation Framework
·         Schedule, Number of resources,Defining SLA,Defining In-Scope/Out-Scope, Return on Investment
3) Environment Setup  

·         Should be setup in Regression enviornment,
·         Licenses
·         Comparison Tool, Text Editor, Supporting Tool
·         AUT access and valid credentials
·         Implementation of automation framework
4) Test Script Development

5) Test Script Execution

6) Test Result Generation and Analysis





Scenario : In Keyword Driven Framework we have Test Case in below format. We need to implement framework in such a way that underlying framework code works like ReflectionAPITestCase.java
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFi6CaxP_kQ-8Lz8ttFJQJvOE09HllzlKx1fYnkeBvdsrIhvGagZW3uJZbA_Vr7a8ikbYW0jwkoHsNIwzT_r4NmE2yhq_gXdECoNPoNtORViMPnR6c1xVxm_vE8kaXF2mc8Sxoh9Nzsm4/s320/Reflection.png




=====================================================================
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionAPITestCase {
   public static void main(String[] args)  {
    
actions.CallMethod("OpenBrowser","","http://www.google.com");
    actions.CallMethod("EnterText", "//input[@id='gs_htif0']", "Selenium");
    actions.CallMethod("ClickButton", "//button[@id='gbqfba']", "");
   }
 
}

====================================================================


Solution :
 Reflection API can be helpful to implement above. It will help you to call methods of a class as shown below

package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class actions {

 
public static void CallMethod(String Action,String Object,String Value) {
    
      Method method= actions.class.getMethod(Action, String.class,String.class);
         method.invoke(Action,Object,Value);
       
        }

        public static void
 OpenBrowser(String Object,String Value){
                System.out.println("Opening browser URL:" + Value );
 }
 
 public static void 
EnterText(String Object,String Value){
        System.out.println("Entering text in : " + Object  + " Value:" + Value) ;
 }
 
 
        public static void 
ClickButton(String Object,String Value){
      System.out.println("Clicking Object : " + Object ) ;
  
       }

 
}



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;


public class ListenerTest {

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        WebDriver web_driver = new FirefoxDriver();
        EventFiringWebDriver driver = new EventFiringWebDriver(web_driver);
        MyListener myListener = new MyListener();
        driver.register(myListener);
       
        driver.navigate().to("http://www.gmail.com");
        driver.findElement(By.xpath("html/body/table[2]/tbody/tr/td[1]/font/table/tbody/tr[3]/td[2]/font/a")).click();
        Thread.sleep(5000L);
        // back button
        System.out.println("Going to click back button");
        driver.navigate().back();
        System.out.println("Clicking back button");
        Thread.sleep(5000L);
        driver.navigate().forward();
        Thread.sleep(5000L);

        driver.quit();
    }

}

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.internal.Coordinates;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.internal.EventFiringMouse;


public class MouseMovement {

   
    public static void main(String[] args) {

       
        WebDriver web_driver = new FirefoxDriver();
        EventFiringWebDriver driver = new EventFiringWebDriver(web_driver);
        MyListener myListener = new MyListener();
        driver.register(myListener);
       
        driver.get("http://timesofindia.com");
        EventFiringMouse mouse = new EventFiringMouse(driver , myListener);
        // move mouse
        Locatable hoverItem = (Locatable) driver.findElement(By.xpath("html/body/div[3]/table[3]/tbody/tr[1]/td[1]/div[12]/div[2]/div[2]/ul/li/a"));
        Coordinates c= hoverItem.getCoordinates();
        try{
            mouse.mouseMove(c);
        }catch(Exception e1){
           
           
        }
        // right click
        driver.findElement(By.xpath("html/body/div[3]/table[3]/tbody/tr[1]/td[1]/div[12]/div[2]/div[2]/ul/li/a")).sendKeys(Keys.chord(Keys.SHIFT,Keys.F10));
        // coordinates
        Point p=driver.findElement(By.xpath("html/body/div[3]/table[3]/tbody/tr[1]/td[1]/div[12]/div[2]/div[2]/ul/li/a")).getLocation();
        System.out.println(p.x);
        System.out.println(p.y);
       
       
       
       
    }

}

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;


public class MyListener extends AbstractWebDriverEventListener{
   
   
    public void afterNavigateBack(WebDriver driver) {
        System.out.println("Hello");
    }

}


package test;

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

public class firefoxprofile {

    public static void main(String[] args){
             
      
   //Below link contains 3 files which if clicked will open Window native window for saving file or open it .
        
// We want to avoid above situation so firefox profile needs to set in such a way that it does not ask anything and download to pre-selected directory.
        // All above needs  profile to be set.

     
   // If you put "about:config" in browser window , you will see all preferences which can be set.
       
      
  FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("browser.download.folderList", 2);
        profile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/msword,application/x-rar-compressed,application/octet-stream,application/csv,text/csv");

       
        
WebDriver driver = new FirefoxDriver(profile);
        driver.get("http://qtpselenium.com/test/testdownload.php");
        driver.findElement(By.xpath("html/body/a[1]")).click();
        driver.findElement(By.xpath("html/body/a[2]")).click();
        driver.findElement(By.xpath("html/body/a[3]")).click();
          
       
       
       
    }
   
   
}


package test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class managingcookies {
 public static void main(String[] args){

  WebDriver driver= new FirefoxDriver();
  driver.get("https://gmail.com");
  
Set<Cookie> cookee= driver.manage().getCookies();
  Iterator<Cookie> it = cookee.iterator() ;

  while(it.hasNext())
  {
  
 Cookie c= it.next();
   
System.out.println(c.getDomain() + c.getName() );
 
  }

  
driver.manage().deleteAllCookies() ;

 }


}




Below code will help you pass dates to method and select the dates on the calender



package test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class calenderhandling {



 public static void main(String[] args)
 {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://spicejet.com/");
  driver.findElement(By.xpath("//input[@name='departDate1text']")).click();

  selectdate("20",driver);
  driver.findElement(By.xpath(".//*[@id='departDate2text']")).click();

  
selectdate("22",driver);
 }


public static void selectdate(String date1, WebDriver driver){
  String xpath ;
  for(int i = 1;i<=5;i++){
       for(int j = 1;j<=7;j++)
  {
        xpath=".//*[@id='ui-datepicker-div']/table/tbody/tr[" + String.valueOf(i) + "]/td[" + String.valueOf(j) + "]";
        
System.out.println(driver.findElement(By.xpath(xpath)).getText());
        if(driver.findElement(By.xpath(xpath)).getText().equals(date1))
        {
         driver.findElement(By.xpath(xpath)).click() ;
         return ;
        }
  }
  }
 
 
 }





}





//Wait for page to load for specified time and if page is not loaded it will throw an exception.


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


import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxDriver;


public class keyboardpress {

    public static void main(String[] args){
       
       
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.rediff.com/");
        driver.findElement(By.xpath("//a[@title='Already a user? Sign in']")).click();
        driver.findElement(By.xpath("//input[@id='c_uname']")).sendKeys(
Keys.ENTER);
       
       
       
    }
   
   
}




Logic : Tabbed window in Webdriver is new window/popup only , so they have same logic for handling. 

Step 1 : When you expect mutiple windows have opened , use 
driver.getWindowHanldes() to get the Handle of all windows.
Step 2 : Pass above object conatining mutiple window to Set object like below
                  
Set<String> win = driver.getWindowHandles();

Step 3 : Pass above Set object to Iterator object 

             
Iterator<String>  it = win.iterator ;

Step 4 : Now use 
next() method of iterator to traverse the iterator and get Window Handle String of desired window.

Step 5 : Once desired Window Handle String is obtained , use below switchTo() method to shift focus.

           
driver.switchTo().window(winpopup) ;


Code Snippet

package test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Tabbedbrowsingandwinpopup {

public static void main(String[] args) {


   WebDriver driver = new FirefoxDriver();
   driver.get("http://www.hdfc.com/") ;
   driver.findElement(By.xpath(".//*[@id='acc-1-head-2']/a")).click();
    driver.findElement(By.xpath(".//*[@id='acc-1-section-2']/li[2]/a")).click(); //Trying to click Call us under Customer Care
  
   
// Above click opens new tab so multiple windows are now open. In Webdriver new tabs are opened in new window.
  
   Set<String> win = driver.getWindowHandles();
  
   
// Window handles are passed to iterator
  
   Iterator<String> it= win.iterator() ;
  
  
// By Default iterator position is before the first element. So first next() will place the iterator at first window handle string
  
   System.out.println(it.next());

 
// Below next() will place iterator to second window handle string(our desired window)
  
   String winpopup= it.next();
  
   
//Use switch to for shifting focus to that new tab/window .
  
   driver.switchTo().window(winpopup) ;
  
   //clicking below on element of new tab

    driver.findElement(By.xpath("html/body/table/tbody/tr[2]/td/table/tbody/tr/td[3]/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[2]/td/p[2]/a")).click();

    
// Above click click on tabbed window has opened popup
   
    win = driver.getWindowHandles();
    it= win.iterator() ;
 
    
// Below next() place focus on first window handle string
   
    System.out.println(it.next());
   
    
// Below next() place focus on tabbed window handle string
   
    System.out.println(it.next());
 
    
// Below next() will give widow string we are desiring
   
    winpopup= it.next();
    driver.switchTo().window(winpopup) ;
    driver.findElement(By.xpath(".//*[@id='popup']/table/tbody/tr/td/table[2]/tbody/tr/td/table[1]/tbody/tr[4]/td/p/font/b/a")).click();

 }


}

Finding Links on Header/Footer and Check for Broken Links

Links on Header/Footer

1) Logic is to find the Header/Footer element by FindElement and then use FindElements to get all <a> tag elements for it. <a> tags are links.


 
WebElement footer= driver.findElement(By.xpath("//div[@id='footer']"));
  int i = footer.findElements(By.tagName("a")).size();

  List<WebElement> footlinks = footer.findElements(By.tagName("a"));


2) Find all broken links : Once you get all link webelement of Footer/Header, click on each of them and check browser title. If browser title has "404" then , the link is broken. You also need to use driver.navigate() here as you have to go forth and back on the page.

Note (very important)  : Make sure you populate "footer" again for each time you come back on main page , as DOM will be changed and simpley traversing the footlinks may not work. 

Code Snippet

package test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class brokenheaderfooter {
 public static void main(String[] args) throws InterruptedException{

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://www.google.com/");  
// Use navigate instead of driver.get() 

WebElement footer= driver.findElement(By.xpath("//div[@id='footer']"));  
// Get Footer element which contains all footer links
  System.out.println(footer.findElements(By.tagName("a")).size()) ; 
  List<WebElement> footlinks = footer.findElements(By.tagName("a"));
  int i = footer.findElements(By.tagName("a")).size(); 
//Get number of links

  for(int j = 0;j<i;j++){    
//create loop based upon number of links to traverse all links
   footer= driver.findElement(By.xpath("//div[@id='footer']"));   
// We are re-creating "footer" webelement as DOM changes after navigate.back()
   footer.findElements(By.tagName("a")).get(j).getText();
   footer.findElements(By.tagName("a")).get(j).click();
      Thread.sleep(3000);
   System.out.println(driver.getTitle());
      if(driver.getTitle().contains("404")) {
       System.out.println("404 Found");
      }
      driver.navigate().back();
   Thread.sleep(4000);
  }
 }
} Links on Header/Footer

1) Logic is to find the Header/Footer element by FindElement and then use FindElements to get all <a> tag elements for it. <a> tags are links.


 
WebElement footer= driver.findElement(By.xpath("//div[@id='footer']"));
  int i = footer.findElements(By.tagName("a")).size();

  List<WebElement> footlinks = footer.findElements(By.tagName("a"));


2) Find all broken links : Once you get all link webelement of Footer/Header, click on each of them and check browser title. If browser title has "404" then , the link is broken. You also need to use driver.navigate() here as you have to go forth and back on the page.

Note (very important)  : Make sure you populate "footer" again for each time you come back on main page , as DOM will be changed and simpley traversing the footlinks may not work. 

Code Snippet

package test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class brokenheaderfooter {
 public static void main(String[] args) throws InterruptedException{
 
  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("
http://www.google.com/");  // Use navigate instead of driver.get() 
 
WebElement footer= driver.findElement(By.xpath("//div[@id='footer']"));  
// Get Footer element which contains all footer links
  System.out.println(footer.findElements(By.tagName("a")).size()) ; 
  List<WebElement> footlinks = footer.findElements(By.tagName("a"));
  int i = footer.findElements(By.tagName("a")).size(); 
//Get number of links
 
  for(int j = 0;j<i;j++){    
//create loop based upon number of links to traverse all links 
   footer= driver.findElement(By.xpath("//div[@id='footer']"));   
// We are re-creating "footer" webelement as DOM changes after navigate.back()
   footer.findElements(By.tagName("a")).get(j).getText();
   footer.findElements(By.tagName("a")).get(j).click();
      Thread.sleep(3000);
   System.out.println(driver.getTitle());
      if(driver.getTitle().contains("404")) {
       System.out.println("404 Found");
      }
      driver.navigate().back();
   Thread.sleep(4000);
  }
 }
}

 Changing firefox Profile - WebDriver


There are situation where you need to change firefoxprofile at run time.

Example are as followed :

1) Accepting untrusted certificates

FirefoxProfile profile= new FirefoxProfile();
profile.setAssumeUntrustedCertificateIssuer(false);

WebDriver driver = new FirefoxDriver(profile);

2) Adding user extension ( like firebug ) at run time

Download the firebug xpi file from mozilla and start the profile as follows:
   
File file = new File("firebug-1.8.1.xpi");
   FirefoxProfile profile = new FirefoxProfile();
   
profile.addExtension(file);
   
profile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen
   
WebDriver driver = new FirefoxDriver(firefoxProfile);


You can also use profile manager manually and assign it to webdriver. Use below code after creating your profilethrough profile manager

One way is:

System.setProperty(“webdriver.firefox.profile”, profileName);
WebDriver webDriver = new FirefoxDriver();


Another way is:

ProfilesIni profilesIni = new ProfilesIni();
// Clone the named profile               
FirefoxProfile profile = profilesIni.getProfile(profileName);
WebDriver webDriver = new FirefoxDriver(profile);


driver.get(https://www.google.com/)  //Load new webpage in current window.

driver.navigate().to("https://www.google.com/") //Also loads webpage in current window , but forward and back button can be used.
          e.g driver.navigate().back();

driver.getCurrentUrl()

driver.getPageSource()

driver.getTitle()

driver.getWindowHandle() //Return an opaque handle to this window that uniquely identifies it within this driver instance. This can be used to switch to this window at a later date

driver.getWindowHandles() //Return a set of window handles which can be used to iterate over all open windows of this webdriver instance by passing them to #switchTo().window(String)

driver.close()  //Close the current window, quitting the browser if it's the last window currently open.

driver.quit()  //Quits this driver, closing every associated window.

There is nothing special about how to get the value of Ajax Droplist. The below code is self-explanatory.

 Few points in below code : 
1) The suggestion are in Table.
2) The number of suggestion is unknown at compile time, so we have to use increasing variable for creating xpath of suggestion element
3) Since loop to get all element will run indefinately so NoSuchElement exception needs to be handled.


package test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class googleajaxlist {
 public static void main(String[] args) throws InterruptedException{
 
  WebDriver driver = new FirefoxDriver();
  driver.get("
https://www.google.com");
  driver.findElement(By.xpath("//input[@class='gbqfif']")).sendKeys("harp");
  Thread.sleep(4000);    
//This sleep is to make sure suggestion got is for word we want.
  int  i = 1;
  String xp;
 
  try {
 
  while(true){
   System.out.println(String.valueOf(i));  
// Needs to convert integer variable to String 
   xp= "//*[@id='gsr']/table/tbody/tr/td[2]/table/tbody/tr[" + String.valueOf(i) + "]/td/div/table/tbody/tr/td[1]";  
//variable xpath string
   System.out.println(xp);
   System.out.println(driver.findElement(By.xpath(xp)).getText()) ;  
// getText() is used to get the suggestion text
   i++;
 
  }
 
  } catch ( NoSuchElementException e ) {};  //Exception handling is done for non-existing element at end of the loop
 
 
   }

}



Step 1: The first step when starting the migration is to change how you obtain your instance of Selenium. When using Selenium RC, this is done like so:

Selenium selenium = new DefaultSelenium("localhost", 4444, "*firefox","http://www.yoursite.com");
selenium.start();



This should be replaced like so:

WebDriver driver = new FirefoxDriver();
Selenium selenium = new WebDriverBackedSelenium(driver, "
http://www.yoursite.com");

Step 2 : Once your tests execute without errors, the next stage is to migrate the actual test code to use the WebDriver APIs. Depending on how well abstracted your code is, this might be a short process or a long one. In either case, the approach is the same and can be summed up simply: modify code to use the new API when you come to edit it.
Assumption : We have MySQL database as backend.
 
 
Step 1 : Download MySQL
clip_image002
Step 2: Navigate to bin directory of SQL server and create some table and insert data as shown below
clip_image004
clip_image006
clip_image008
clip_image010
clip_image012
clip_image014
clip_image016
clip_image018
clip_image020
 
Step 3 : Now in Eclipse you need jar for database connectivity . The jar contains jar for drivers.  MySql database has different jar and Oracle would have different.
 
Download jar for Mysql connectivity
clip_image022
 
Step 4 :  Lets create fresh project for testing database testing. You can create Class in existing project also.
 
Create project
clip_image024
 
Step 5 : Add MySql jar in the Build Path of the project
Step 6 : Follow below steps in the created class for performing below functions;
 

·         Select
·         Select with condition
·         Insert
 
 

·         import package java.sql.* : All database connectivity related classes are present here.
·         Add jar of mysql database connectivity
·         Interface “Connection” in java helps to connect to database . It has many methods
clip_image026

·         Above Driver does all the magic to connect
·         All database connectivity should be in try catch
clip_image028
 
Code Snippet
 
import java.sql.*;
public class dbconnectclass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{

//Below is standard variables which you need to set for database connectivity

Connection conn = null;  //Create object of Connection object 
String url = "jdbc:mysql://localhost:3306/"; 
String driver = "com.mysql.jdbc.Driver"; //different for Oracleor other databases
String dbname ="test"; 
String userName= "root"; 
String password ="password";


try {

Class.forName(driver).newInstance(); 
//create object of Driver class

conn=DriverManager.getConnection(url+dbname,userName,password); 
//connection will be established from this line 


//***********Statement***********Without condition Select Statement*********
Statement stmt = conn.createStatement();    
ResultSet rs = stmt.executeQuery("select * from users"); 
rs.next() ; //1st Row
System.out.println(rs.getString("name")); //column
rs.next() ; //2nd Row
System.out.println(rs.getString(1));
// to print whole table
// mind it rs is at the 3rd row.
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) ); 
}
//********Prepared statement**select**********
//Prepared Statement is used for sql statement with conditional statements
PreparedStatement pstmt= conn.prepareStatement("select * from users where name = ? and sex= ? ");
pstmt.setString(1, "B");
pstmt.setString(2, "F");
ResultSet rs1=pstmt.executeQuery(); 
while(rs1.next()){
System.out.println(rs1.getString(1) + " " + rs1.getString(2) + " " + rs1.getString(3) );
}
//********Prepared statement**insert**********
//Prepared Statement is used for sql statement with conditional statements
PreparedStatement pstmt1= conn.prepareStatement("insert into users values(?,?,?)");
pstmt1.setString(1, "Tom");
pstmt1.setString(2, "London");
pstmt1.setString(3, "M");
pstmt1.executeUpdate();
System.out.println("Inserted");
catch (Exception e) {
}finally {
conn.close();
}
}


package test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class maximizewind {

 public static void main(String[] args){ 

  WebDriver driver = new FirefoxDriver();
       driver.get("https://www.google.com/");
       
driver.manage().window().maximize();
   

}
 }
 


package test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.internal.selenesedriver.TakeScreenshot;
public class takingscrshot {

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

 WebDriver driver= new FirefoxDriver();
 driver.get("https://www.google.com/");

 
File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
 FileUtils.copyFile(scrFile, new File("C:\\Local Disk D_9220122129\\tmp.jpg"));


}

}

How to get values from some Config/text files through Properties Class



Step 1 : Create file and put values like below in it and place it in some package.

e.g config.properties

firstname=harry
lastname=mohan


Step 2 : Use
 System.getProperty("user.dir") to get the relative path of workspace . This way you can make config.properties as machine independent

Step 3 : Use below code . It has all detail about further steps

package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class propfilelearning {
 public static void main(String[] args) throws IOException{

  //Create Object of Properties Class

  
Properties prop = new Properties();

  //Use System.getProperty to get the relative path of file in Workspace. Now file path is machine independent.
  String path = System.getProperty("user.dir") + "\\src\\test\\config.properties";
  System.out.println("Actual Location of File -> " + path);


  //Create FileInputStream object of Config/data file
  
FileInputStream fs= new FileInputStream(path);

  // Pass fs object to load method of Properties object

 
 prop.load(fs);

  // Use getProperty method of Properties object to get the values.

 
 System.out.println(prop.getProperty("firstname"));
  System.out.println(prop.getProperty("lastname"));
 
 }
}


I had to run the Webdriver scripts on a Firefox and I had to use a particular proxy to get access to the
QA/Dev environment. Here is the code that you can use to change the proxy settings.


FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("network.proxy.type", 1);
firefoxProfile.setPreference("network.proxy.http", "100.00.100.100");
firefoxProfile.setPreference("network.proxy.http_port", 80);
firefoxProfile.setPreference("network.proxy.ssl", "100.00.100.100");
firefoxProfile.setPreference("network.proxy.ssl_port", 80);
firefoxProfile.setPreference("network.proxy.no_proxies_on", "");
driver = new FirefoxDriver(firefoxProfile);




Make changes to the PROXY_HOST – “100.00.100.100″ and the PROXY_PORT – 80. The PROXY_PORT is an Integer and PROXY_HOST is a String.


package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class titlebrow {

 public static void main(String[] args){

  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.rediff.com/");
  
System.out.println("Title is : " + driver.getTitle());

 }
}
package test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class handlingalert {

 public static void main(String[] args){

  WebDriver driver = new FirefoxDriver();
  driver.get("http://www.rediff.com/");
  driver.findElement(By.xpath("//a[@title='Already a user? Sign in']")).click();
  driver.findElement(By.xpath("//input[@id='btn_login']")).click();
 
 driver.switchTo().alert().accept() ;

  
//If you want to do some operations or validations on alert below code is helpful
  driver.findElement(By.xpath("//input[@id='btn_login']")).click();
 
 Alert al = driver.switchTo().alert();
  System.out.println(al.getText());
 // 
al.dismiss(); //only if cancel is there . In our case cancel is not there.

 }
}

Below Code Handles iFrame on one of the website


package test;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class iframelearn {
public static void main(String[] args ) throws InterruptedException{

WebDriver driver = new FirefoxDriver();
driver.get("http://borro.com/start");
driver.findElement(By.xpath("//a[@class='iframe-callback top-link-red']")).click();
Thread.sleep(1000L);
//Below listing of frame is done as we could not find iframe tag in the view source
List<WebElement> frames = driver.findElements(By.tagName("iFrame"));
System.out.println("Total Frames -> " + frames.size());

//Size of frames is 2 but we dont know which is our frame, so do hit and trial by finding desired frame element . If not found on first try on second.In our case it is on second frame.
driver.switchTo().frame(1);
//Enter into first element on the frame
driver.findElement(By.id("firstname")).sendKeys("Harpreat");
//If you want to get id of frames use below code. Position of code may be incorrect.
System.out.println(frames.get(0).getAttribute("id"));
System.out.println(frames.get(1).getAttribute("id"));

}
}



Extract all links from a webpage using webdriver for selenium automation testing

mport java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class dadabhagwan_LearnSeleniumWithJasmine {
public static void main(String[] args) throws InterruptedException {
WebDriver myDriver = new FirefoxDriver();
myDriver.get("http://satsang.dadabhagwan.org/");
/*Extract all links from the webpage using selenium webdriver*/
List all_links_webpage = myDriver.findElements(By.tagName("a"));
/*Print total no of links on the webpage*/
System.out.println("Print total no of links on the webpage---------------------------------------------");
System.out.println(all_links_webpage.size());

/*Print text of all links*/
System.out.println("Print text of all links------------------------------------------------------------");
for(int i=0;i
System.out.println(all_links_webpage.get(i).getText());
}

/*Print Links*/
System.out.println("Print Links------------------------------------------------------------------------");
for(int i=0;i
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}


/*Extract all links from the part of the webpage using selenium webdriver*/
System.out.println("Extract all links from the part of the webpage using selenium webdriver-----------------------------");
List myList = myDriver.findElement(By.xpath("//*[@id='Flot']")).findElements(By.tagName("a"));
System.out.println("total no links on specific part of webpage---------------------------------------------------");
System.out.println(myList.size());
System.out.println("Text of the link for specific part of webpage--------------------------------------------------");
for(int i =0; i< myList.size();i++){
System.out.println(myList.get(i).getText());
}
}
}


Use below statement in you code if you want to pause execution of your run.

Thread.sleep(4000) ;  //for 4 seconds

Note : Above statment throws "InterruptedException" , so need to handle in the method.



Selenium Grid Installations

Download Required

1) selenium-server-standalone-ver.jar : All client machines and Server Machine


Steps : 

Step 1 : 
Start the hub : Start hub on the Server machine with below command

java -jar selenium-server-standalone-2.28.0.jar -role hub

The hub will automatically start-up using port 4444 by default. To change the default port, you can add the optional parameter -port when you run the command. You can view the status of the hub by opening a browser window and navigating to: http://localhost:4444/grid/console 

Step 2: Start the nodes : Regardless on whether you want to run a grid with new WebDriver functionality, or a grid with Selenium 1 RC functionality, or both at the same time, you use the same selenium-server-standalone jar file to start the nodes.

java -jar selenium-server-standalone-2.14.0.jar -role node  -hub http://localhost:4444/grid/register

-browser  browserName=firefox,version=3.6,maxInstances=5,platform=LINUX : This can be supplied .
For Windows : platform=WINDOWS
Note: The port defaults to 5555 if not specified whenever the "-role" option is provided and is not hub.


Using grid to run tests

 

For WebDriver nodes, you will need to use the RemoteWebDriver and the DesiredCapabilities object to define which browser, version and platform you wish to use. Create the target browser capabilities you want to run the tests against:

 

DesiredCapabilities capability = DesiredCapabilities.firefox();

 

Pass that into the RemoteWebDriver object:
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
The hub will then assign the test to a matching node.
A node matches if all the requested capabilities are met. To request specific capabilities on the grid, specify them before passing it into the WebDriver object.
capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);
Example: A node registered with the setting:
 -browser  browserName=firefox,version=3.6,platform=LINUX
will be a match for:
capability.setBrowserName(“firefox ); 
capability.setPlatform(“LINUX”);  
capability.setVersion(“3.6”);
and would also be a match for
capability.setBrowserName(“firefox ); 
capability.setVersion(“3.6”);

Code Snippet : 

import java.net.MalformedURLException;
import java.net.URL;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;


public class testremote {

    @Test
    public void test1() throws MalformedURLException{
   
    DesiredCapabilities capability = DesiredCapabilities.firefox();
    capability.setBrowserName("firefox"); 
    capability.setVersion("18.0.2");
    WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
    driver.get("http://google.com");
   
   
}
   
}


 


package excel;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

/**
 * A simple POI example of opening an Excel spreadsheet
 * and writing its contents to the command line.
 * @author  Tony Sintes
 */
public class POIExample {

    public static void main(String[] args) {
        String fileName = "C:\\testPOIWrite.xls";
        writeDataToExcelFile(fileName);
        readDataToExcelFile(fileName);
    }

    public static void readDataToExcelFile(String fileName){
        try{
            FileInputStream fis = new FileInputStream(fileName);
            HSSFWorkbook workbook = new HSSFWorkbook(fis);
            HSSFSheet sheet = workbook.getSheetAt(0);

            for (int rowNum = 0; rowNum < 10; rowNum++) {
                for (int cellNum = 0; cellNum < 5; cellNum++) {
                    HSSFCell cell = sheet.getRow(rowNum).getCell(cellNum);
                    System.out.println(rowNum+":"+cellNum+" = " + cell.getStringCellValue());
                }
            }
            
            fis.close();
        }catch(Exception e){
            e.printStackTrace();
        }


    }
    public static void writeDataToExcelFile(String fileName) {
        try {

            HSSFWorkbook myWorkBook = new HSSFWorkbook();
            HSSFSheet mySheet = myWorkBook.createSheet();
            HSSFRow myRow;
            HSSFCell myCell;

            for (int rowNum = 0; rowNum < 10; rowNum++) {
                myRow = mySheet.createRow(rowNum);
                for (int cellNum = 0; cellNum < 5; cellNum++) {
                    myCell = myRow.createCell(cellNum);
                    myCell.setCellValue(new HSSFRichTextString(rowNum + "," + cellNum));
                }
            }


            FileOutputStream out = new FileOutputStream(fileName);
            myWorkBook.write(out);
            out.flush();
            out.close();
            

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





public class testclass {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://somedomain/url_that_delays_loading");
   

 // Below is one way of implemening
          WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(new ExpectedCondition<WebElement>(){
            @Override
            public WebElement apply(WebDriver d) {
                return d.findElement(By.id("myDynamicElement"));
            }});
 
//Second easy way of implementing
       WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("someid")));

          }}


  
    }}

Above is explicit wait where you define code to wait for a certain condition to occur before proceeding further in the code. 
WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

This waits up to 10 seconds before throwing a 
TimeoutException or if it finds the element will return it in 0 - 10 seconds.WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.


Expected Condition :  There are some common conditions that are frequently come across when automating web browsers. Listed below are Implementations of each. Java happens to have convienence methods so you don’t have to code an ExpectedCondition class yourself or create your own utility package for them. Refer below for some of the condition

http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html

Java Casting

Getting a String out of an ArrayList


String StringName = (String)arrayListName.get(n);


Note : Double is a class while double is a primitive 

Getting a double out of an ArrayList (Stored in the ArrayList as a Double)


double doubName = ((Double)arrayListName.get(n)).doubleValue();


String to Double to double (using Double constructor)


double doubName = new Double(stringName).doubleValue;

String to Double to double


double doubName = Double.valueOf(stringName).doubleValue;

String to double (using static Double method - Java 1.2 & later)


double doubName = Double.parseDouble(stringName);

double to a new String (using the String constructor)


String stringName = new String(doubleName);

double to existing String


stringName = String.valueOf(doubleName);

double to int


double doubleName = 3;
int intName = (int)doubleName;  
  // intName becomes == 3
double anotherDoubleName = 3.3;
int anotherIntName = (int)anotherDoubleName;  
  //anotherIntName becomes == 3, not 3.3

String to char


char charName = stringName.charAt(2); 
  //must specify offset in string to get char from

TestNG is a testing framework designed to simply a broad range of testing needs, from unit testing (testing a class in isolation of the others) to integration testing (testing entire systems made of several classes, several packages and even several external frameworks, such as application servers).

Writing a test is typically a three-step process: 
•    
Write the business logic of your test and insert TestNG annotations in your code.
•    
Add the information about your test (e.g. the class name, the groups you wish to run, etc...) in a testng.xml file or in build.xml.
•    
Run TestNG.


You can find a quick example on the Welcome page.
The concepts used in this documentation are as follows:
•    A suite is represented by one XML file. It can contain one or more tests and is defined by the <suite> tag.
•    A test is represented by <test> and can contain one or more TestNG classes.
•    A TestNG class is a Java class that contains at least one TestNG annotation. It is represented by the <class> tag and can contain one or more test methods.
•    A test method is a Java method annotated by @Test in your source.


Question : What kind of method on Before Suite and After suite ?

You can invoke TestNG in several different ways:
•    With a testng.xml file
•    With ant
•    From the command line

The current DTD for testng.xml can be found on the main Web site:  http://testng.org/testng-1.0.dtd (for your convenience, you might prefer to browse the HTML version).


TestNG can be invoked in different ways:
•    Command line
•    ant
•    Eclipse
•    IntelliJ's IDEA

Assuming that you have TestNG in your class path, the simplest way to invoke TestNG is as follows:
java org.testng.TestNG testng1.xml [testng2.xml testng3.xml ...]

You need to specify at least one XML file describing the TestNG suite you are trying to run. Additionally, the following command-line switches are available:

Option    Argument    Documentation
-configfailurepolicy    skip|continue    Whether TestNG should continue to execute the remaining tests in the suite or skip them if an @Before* method fails. Default behavior is skip.
-d    A directory    The directory where the reports will be generated (defaults to test-output).
-dataproviderthreadcount    The default number of threads to use for data providers when running tests in parallel.    This sets the default maximum number of threads to use for data providers when running tests in parallel. It will only take effect if the parallel mode has been selected (for example, with the -parallel option). This can be overridden in the suite definition.
-excludegroups    A comma-separated list of groups.    The list of groups you want to be excluded from this run.
-groups    A comma-separated list of groups.    The list of groups you want to run (e.g. "windows,linux,regression").
-listener    A comma-separated list of Java classes that can be found on your classpath.    Lets you specify your own test listeners. The classes need to implement org.testng.ITestListener

-methods    A comma separated list of fully qualified class name and method. For example com.example.Foo.f1,com.example.Bar.f2.    Lets you specify individual methods to run.
-methodselectors    A comma-separated list of Java classes and method priorities that define method selectors.    Lets you specify method selectors on the command line. For example: com.example.Selector1:3,com.example.Selector2:2
-parallel    methods|tests|classes    If specified, sets the default mechanism used to determine how to use parallel threads when running tests. If not set, default mechanism is not to use parallel threads at all. This can be overridden in the suite definition.
-reporter    The extended configuration for a custom report listener.    Similar to the -listener option, except that it allows the configuration of JavaBeans-style properties on the reporter instance.
Example: -reporter com.test.MyReporter:methodFilter=*insert*,enableFiltering=true
You can have as many occurences of this option, one for each reporter that needs to be added.
-sourcedir    A semi-colon separated list of directories.    The directories where your javadoc annotated test sources are. This option is only necessary if you are using javadoc type annotations. (e.g. "src/test" or "src/test/org/testng/eclipse-plugin;src/test/org/testng/testng").
-suitename    The default name to use for a test suite.    This specifies the suite name for a test suite defined on the command line. This option is ignored if the suite.xml file or the source code specifies a different suite name. It is possible to create a suite name with spaces in it if you surround it with double-quotes "like this".
-testclass    A comma-separated list of classes that can be found in your classpath.    A list of class files separated by commas (e.g. "org.foo.Test1,org.foo.test2").
-testjar    A jar file.    Specifies a jar file that contains test classes. If a testng.xml file is found at the root of that jar file, it will be used, otherwise, all the test classes found in this jar file will be considered test classes.
-testname    The default name to use for a test.    This specifies the name for a test defined on the command line. This option is ignored if the suite.xml file or the source code specifies a different test name. It is possible to create a test name with spaces in it if you surround it with double-quotes "like this".
-testnames    A comma separated list of test names.    Only tests defined in a <test> tag matching one of these names will be run.
-testrunfactory    A Java classes that can be found on your classpath.    Lets you specify your own test runners. The class needs to implement org.testng.ITestRunnerFactory.

-threadcount    The default number of threads to use when running tests in parallel.    This sets the default maximum number of threads to use for running tests in parallel. It will only take effect if the parallel mode has been selected (for example, with the -parallel option). This can be overridden in the suite definition.
-xmlpathinjar    The path of the XML file inside the jar file.    This attribute should contain the path to a valid XML file inside the test jar (e.g. "resources/testng.xml"). The default is "testng.xml", which means a file called "testng.xml" at the root of the jar file. This option will be ignored unless -testjar is specified.
This documentation can be obtained by invoking TestNG without any arguments.


You can also put the command line switches in a text file, say c:\command.txt, and tell TestNG to use that file to retrieve its parameters:
C:> more c:\command.txt
-d test-output testng.xml
C:> java org.testng.TestNG @c:\command.txt



Note: TestNG uses regular expressions, and not wildmats. Be aware of the difference (for example, "anything" is matched by ".*" -- dot star -- and not "*").

5.1 - Test groups

TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set.  This gives you maximum flexibility in how you partition your tests and doesn't require you to recompile anything if you want to run two different sets of tests back to back.
Groups are specified in your testng.xml file and can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath. Note that groups are accumulative in these tags: if you specify group "a" in <suite> and "b" in <test>, then both "a" and "b" will be included.
For example, it is quite common to have at least two categories of tests
•    Check-in tests.  These tests should be run before you submit new code.  They should typically be fast and just make sure no basic functionality was broken.

•    Functional tests.  These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously.
Typically, check-in tests are a subset of functional tests.  TestNG allows you to specify this in a very intuitive way with test groups.  For example, you could structure your test by saying that your entire test class belongs to the "functest" group, and additionally that a couple of methods belong to the group "checkintest":
Test1.java
view source
print?
public class Test1 {
  @Test(groups = { "functest", "checkintest" })
  public void testMethod1() {
  }

  @Test(groups = {"functest", "checkintest"} )
  public void testMethod2() {
  }

  @Test(groups = { "functest" })
  public void testMethod3() {
  }
}
Invoking TestNG with
testng.xml
<test name="Test1">
  <groups>
    <run>
      <include name="functest"/>
    </run>
  </groups>
  <classes>
    <class name="example1.Test1"/>
  </classes>
</test>
will run all the test methods in that classes, while invoking it with checkintest will only run testMethod1() and testMethod2().
Here is another example, using regular expressions this time.  Assume that some of your test methods should not be run on Linux, your test would look like:
Test1.java
@Test
public class Test1 {
  @Test(groups = { "windows.checkintest" })
  public void testWindowsOnly() {
  }

  @Test(groups = {"linux.checkintest"} )
  public void testLinuxOnly() {
  }

  @Test(groups = { "windows.functest" )
  public void testWindowsToo() {
  }
}
You could use the following testng.xml to launch only the Windows methods:
testng.xml
view source
print?
<test name="Test1">
  <groups>
    <run>
      <include name="windows.*"/>
    </run>
  </groups>

  <classes>
    <class name="example1.Test1"/>
  </classes>
</test>
Note: TestNG uses regular expressions, and not wildmats. Be aware of the difference (for example, "anything" is matched by ".*" -- dot star -- and not "*").


Method groups
You can also exclude or include individual methods:
testng.xml
view source
print?
<test name="Test1">
  <classes>
    <class name="example1.Test1">
      <methods>
        <include name=".*enabledTestMethod.*"/>
        <exclude name=".*brokenTestMethod.*"/>
      </methods>
     </class>
  </classes>
</test>
This can come in handy to deactivate a single method without having to recompile anything, but I don't recommend using this technique too much since it makes your testing framework likely to break if you start refactoring your Java code (the regular expressions used in the tags might not match your methods any more).


5.3 - Exclusion group


All I need to do now is to exclude this group from the run:
testng.xml
view source
print?
<test name="Simple example">
  <groups>
    <run>
      <include name="checkintest"/>
      <exclude name="broken"/>
    </run>
  </groups>
 
  <classes>
    <class name="example1.Test1"/>
  </classes>
</test>


5.4 - Partial groups
You can define groups at the class level and then add groups at the method level:
All.java
view source
print?
@Test(groups = { "checkin-test" })
public class All {

  @Test(groups = { "func-test" )
  public void method1() { ... }

  public void method2() { ... }
}
In this class, method2() is part of the group "checkin-test", which is defined at the class level, while method1() belongs to both "checkin-test" and "func-test".


5.5 - Parameters
Test methods don't have to be parameterless.  You can use an arbitrary number of parameters on each of your test method, and you instruct TestNG to pass you the correct parameters with the @Parameters annotation.
There are two ways to set these parameters:  with testng.xml or programmatically.
  5.5.1 - Parameters from testng.xml
If you are using simple values for your parameters, you can specify them in your testng.xml:
Java
view source
print?
@Parameters({ "first-name" })
@Test
public void testSingleString(String firstName) {
  System.out.println("Invoked testString " + firstName);
  assert "Cedric".equals(firstName);
}
In this code, we specify that the parameter firstName of your Java method should receive the value of the XML parameter called first-name.  This XML parameter is defined in testng.xml:
testng.xml
view source
print?
<suite name="My suite">
  <parameter name="first-name"  value="Cedric"/>
  <test name="Simple example">
  <-- ... -->
The same technique can be used for @Before/After and @Factory annotations:
view source
print?
@Parameters({ "datasource", "jdbcDriver" })
@BeforeMethod
public void beforeTest(String ds, String driver) {
  m_dataSource = ...;                              // look up the value of datasource
  m_jdbcDriver = driver;
}
This time, the two Java parameter ds and driver will receive the value given to the properties datasource and jdbc-driver respectively. 
Parameters can be declared optional with the Optional annotation:
view source
print?
@Parameters("db")
@Test
public void testNonExistentParameter(@Optional("mysql") String db) { ... }
If no parameter named "db" is found in your testng.xml file, your test method will receive the default value specified inside the @Optional annotation: "mysql".
The @Parameters annotation can be placed at the following locations:
•    On any method that already has a @Test, @Before/After or @Factory annotation.
•    On at most one constructor of your test class.  In this case, TestNG will invoke this particular constructor with the parameters initialized to the values specified in testng.xml whenever it needs to instantiate your test class.  This feature can be used to initialize fields inside your classes to values that will then be used by your test methods.
Notes:
•    The XML parameters are mapped to the Java parameters in the same order as they are found in the annotation, and TestNG will issue an error if the numbers don't match.
•    Parameters are scoped. In testng.xml, you can declare them either under a <suite> tag or under <test>. If two parameters have the same name, it's the one defined in <test> that has precedence. This is convenient if you need to specify a parameter applicable to all your tests and override its value only for certain tests.


5.6 - Dependent methods
Sometimes, you need your test methods to be invoked in a certain order.  This is useful for example
•    To make sure a certain number of test methods have completed and succeeded before running more test methods.
•    To initialize your tests while wanting this initialization methods to be test methods as well (methods tagged with @Before/After will not be part of the final report).
In order to do this, you can use the attributes dependsOnMethods or dependsOnGroups, found on the @Test annotation.
There are two kinds of dependencies:
•    Hard dependencies. All the methods you depend on must have run and succeeded for you to run. If at least one failure occurred in your dependencies, you will not be invoked and marked as a SKIP in the report.
•    Soft dependencies. You will always be run after the methods you depend on, even if some of them have failed. This is useful when you just want to make sure that your test methods are run in a certain order but their success doesn't really depend on the success of others. A soft dependency is obtained by adding "alwaysRun=true" in your @Test annotation.
Here is an example of a hard dependency:
view source
print?
@Test
public void serverStartedOk() {}

@Test(dependsOnMethods = { "serverStartedOk" })
public void method1() {}
In this example, method1() is declared as depending on method serverStartedOk(), which guarantees that serverStartedOk() will always be invoked first.
You can also have methods that depend on entire groups:
view source
print?
@Test(groups = { "init" })
public void serverStartedOk() {}

@Test(groups = { "init" })
public void initEnvironment() {}

@Test(dependsOnGroups = { "init.* })
public void method1() {}
In this example, method1() is declared as depending on any group matching the regular expression "init.*", which guarantees that the methods serverStartedOk() and initEnvironment() will always be invoked before method1(). 
Note:  as stated before, the order of invocation for methods that belong in the same group is not guaranteed to be the same across test runs.
If a method depended upon fails and you have a hard dependency on it (alwaysRun=false, which is the default), the methods that depend on it are not marked as FAIL but as SKIP.  Skipped methods will be reported as such in the final report (in a color that is neither red nor green in HTML), which is important since skipped methods are not necessarily failures.
Both dependsOnGroups and dependsOnMethods accept regular expressions as parameters.  For dependsOnMethods, if you are depending on a method which happens to have several overloaded versions, all the overloaded methods will be invoked.  If you only want to invoke one of the overloaded methods, you should use dependsOnGroups.


5.8 - Class level annotations
The @Test annotation can be put on a class instead of a test method:
Test1.java
view source
print?
@Test
public class Test1 {
  public void test1() {
  }

  public void test2() {
  }
}
The effect of a class level @Test annotation is to make all the public methods of this class to become test methods even if they are not annotated. You can still repeat the @Test annotation on a method if you want to add certain attributes.
For example:
Test1.java
view source
print?
@Test
public class Test1 {
  public void test1() {
  }

  @Test(groups = "g1")
  public void test2() {
  }
}
will make both test1() and test2() test methods but on top of that, test2() now belongs to the group "g1".


5.9 - Parallelism and time-outs
You can instruct TestNG to run your tests in separate threads in various ways.
5.9.1 - Parallel suites
This is useful if you are running several suite files (e.g. "java org.testng.TestNG testng1.xml testng2.xml") and you want each of these suites to be run in a separate thread. You can use the following command line flag to specify the size of a thread pool:
view source
print?
java org.testng.TestNG -suitethreadpoolsize 3 testng1.xml testng2.xml testng3.xml
The corresponding ant task name is suitethreadpoolsize.
5.9.2 - Parallel tests, classes and methods
The parallel attribute on the <suite> tag can take one of following values:
view source
print?
<suite name="My suite" parallel="methods" thread-count="5">
view source
print?
<suite name="My suite" parallel="tests" thread-count="5">
view source
print?
<suite name="My suite" parallel="classes" thread-count="5">
•    parallel="methods": TestNG will run all your test methods in separate threads. Dependent methods will also run in separate threads but they will respect the order that you specified.

•    parallel="tests": TestNG will run all the methods in the same <test> tag in the same thread, but each <test> tag will be in a separate thread. This allows you to group all your classes that are not thread safe in the same <test> and guarantee they will all run in the same thread while taking advantage of TestNG using as many threads as possible to run your tests.

•    parallel="classes": TestNG will run all the methods in the same class in the same thread, but each class will be run in a separate thread.
Additionally, the attribute thread-count allows you to specify how many threads should be allocated for this execution.
Note: the @Test attribute timeOut works in both parallel and non-parallel mode.
You can also specify that a @Test method should be invoked from different threads. You can use the attribute threadPoolSize to achieve this result:
view source
print?
@Test(threadPoolSize = 3, invocationCount = 10,  timeOut = 10000)
public void testServer() {
In this example, the function testServer will be invoked ten times from three different threads. Additionally, a time-out of ten seconds guarantees that none of the threads will block on this thread forever.


5.10 - Rerunning failed tests
Every time tests fail in a suite, TestNG creates a file called testng-failed.xml in the output directory. This XML file contains the necessary information to rerun only these methods that failed, allowing you to quickly reproduce the failures without having to run the entirety of your tests.  Therefore, a typical session would look like this:
view source
print?
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs testng.xml
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -d test-outputs test-outputs\testng-failed.xml
Note that testng-failed.xml will contain all the necessary dependent methods so that you are guaranteed to run the methods that failed without any SKIP failures.



5.11 - JUnit tests
TestNG can run JUnit 3 tests (JUnit 4 is not supported).  All you need to do is specify your JUnit test classes in the testng.classNames property and set the testng.junit property to true:
testng.xml
view source
print?
<test name="Test1" junit="true">
  <classes>
    <!-- ... -->
The behavior of TestNG in this case is similar to JUnit:
•    All methods starting with test* in your classes will be run
•    If there is a method setUp() on your test class, it will be invoked before every test method
•    If there is a method tearDown() on your test class, it will be invoked before after every test method
•    If your test class contains a method suite(), all the tests returned by this method will be invoked


6 - Test results
6.1 - Success, failure and assert
A test is considered successful if it completed without throwing any exception or if  it threw an exception that was expected (see the documentation for the expectedExceptions attribute found on the @Test annotation).
Your test methods will typically be made of calls that can throw an exception, or of various assertions (using the Java "assert" keyword).  An "assert" failing will trigger an AssertionErrorException, which in turn will mark the method as failed (remember to use -ea on the JVM if you are not seeing the assertion errors).
Here is an example test method:
view source
print?
@Test
public void verifyLastName() {
  assert "Beust".equals(m_lastName) : "Expected name Beust, for" + m_lastName;
}
TestNG also include JUnit's Assert class, which lets you perform assertions on complex objects:
view source
print?
import static org.testng.AssertJUnit.*;
//...
@Test
public void verify() {
  assertEquals("Beust", m_lastName);
}
Note that the above code use a static import in order to be able to use the assertEquals method without having to prefix it by its class.


6.2 - Logging and results
The results of the test run are created in a file called index.html in the directory specified when launching SuiteRunner.  This file points to various other HTML and text files that contain the result of the entire test run.  You can see a typical example here.
It's very easy to generate your own reports with TestNG with Listeners and Reporters:
•    Listeners implement the interface org.testng.ITestListener and are notified in real time of when a test starts, passes, fails, etc...
•    Reporters implement the interface org.testng.IReporter and are notified when all the suites have been run by TestNG. The IReporter instance receives a list of objects that describe the entire test run.
For example, if you want to generate a PDF report of your test run, you don't need to be notified in real time of the test run so you should probably use an IReporter. If you'd like to write a real-time reporting of your tests, such as a GUI with a progress bar or a text reporter displaying dots (".") as each test is invoked (as is explained below), ITestListener is your best choice.
  6.2.1 - Logging Listeners
Here is a listener that displays a "." for each passed test, a "F" for each failure and a "S" for each skip:
view source
print?
public class DotTestListener extends TestListenerAdapter {
  private int m_count = 0;

  @Override
  public void onTestFailure(ITestResult tr) {
    log("F");
  }

  @Override
  public void onTestSkipped(ITestResult tr) {
    log("S");
  }

  @Override
  public void onTestSuccess(ITestResult tr) {
    log(".");
  }

  private void log(String string) {
    System.out.print(string);
    if (++m_count % 40 == 0) {
      System.out.println("");
    }
  }
}
In this example, I chose to extend TestListenerAdapter, which implements ITestListener with empty methods, so I don't have to override other methods from the interface that I have no interest in. You can implement the interface directly if you prefer.
Here is how I invoke TestNG to use this new listener:
Shell
view source
print?
java -classpath testng.jar;%CLASSPATH% org.testng.TestNG -listener org.testng.reporters.DotTestListener test\testng.xml
and the output:
Shell
view source
print?
........................................
........................................
........................................
........................................
........................................
.........................
===============================================
TestNG JDK 1.5
Total tests run: 226, Failures: 0, Skips: 0
===============================================
Note that when you use -listener, TestNG will automatically determine the type of listener you want to use.
  6.2.2 - Logging Reporters
The org.testng.IReporter interface only has one method:
view source
print?
public void generateReport(List<ISuite> suites, String outputDirectory)
This method will be invoked by TestNG when all the suites have been run and you can inspect its parameters to access all the information on the run that was just completed.
  6.2.3 - JUnitReport
TestNG contains a listener that takes the TestNG results and outputs an XML file that can then be fed to JUnitReport. Here is an example, and the ant task to create this report:
build.xml
view source
print?
<target name="reports">
  <junitreport todir="test-report">
    <fileset dir="test-output">
      <include name="*/*.xml"/>
    </fileset>
 
    <report format="noframes"  todir="test-report"/>
  </junitreport>
</target>
Note:  a current incompatibility between the JDK 1.5 and JUnitReports prevents the frame version from working, so you need to specify "noframes" to get this to work for now.
  6.2.4 - Reporter API
If you need to log messages that should appear in the generated HTML reports, you can use the class org.testng.Reporter:
    Reporter.log("M3 WAS CALLED"); 

TestNG Tutorial

TestNG Tutorial 1 – Basic usage


This tutorial introduces the basic annotation supported in TestNG.
import java.util.*;
import org.testng.Assert;
import org.testng.annotations.*;

public class TestNGTest1 {

    private Collection collection;

    @BeforeClass
    public void oneTimeSetUp() {
        // one-time initialization code   
        System.out.println("@BeforeClass - oneTimeSetUp");
    }

    @AfterClass
    public void oneTimeTearDown() {
        // one-time cleanup code
        System.out.println("@AfterClass - oneTimeTearDown");
    }

    @BeforeMethod
    public void setUp() {
        collection = new ArrayList();
        System.out.println("@BeforeMethod - setUp");
    }

    @AfterMethod
    public void tearDown() {
        collection.clear();
        System.out.println("@AfterMethod - tearDown");
    }

    @Test
    public void testEmptyCollection() {
        Assert.assertEquals(collection.isEmpty(),true);
        System.out.println("@Test - testEmptyCollection");
    }

    @Test
    public void testOneItemCollection() {
        collection.add("itemA");
        Assert.assertEquals(collection.size(),1);
        System.out.println("@Test - testOneItemCollection");
    }
}
Result
@BeforeClass - oneTimeSetUp
@BeforeMethod - setUp
@Test - testEmptyCollection
@AfterMethod - tearDown
@BeforeMethod - setUp
@Test - testOneItemCollection
@AfterMethod - tearDown
@AfterClass - oneTimeTearDown
PASSED: testEmptyCollection
PASSED: testOneItemCollection

 

TestNG Tutorial 2 – Expected Exception Test


import org.testng.annotations.*;

/**
 * TestNG Expected Exception Test
 * @author mkyong
 *
 */
public class TestNGTest2 {

    @Test(expectedExceptions = ArithmeticException.class)  
    public void divisionWithException() {  
      int i = 1/0;
    }  

}
In above example, the divisionWithException() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass.

TestNG Tutorial 3 – Ignore Test


This “Ignored” means the method is not ready to test, the TestNG engine will just bypass this method.
import org.testng.annotations.*;

/**
 * TestNG Ignore Test
 * @author mkyong
 *
 */
public class TestNGTest3 {

    @Test(
enabled=false)
    public void divisionWithException() {  
      System.out.println("Method is not ready yet");
    }  

}
In above example, TestNG will not test the divisionWithException() method.

TestNG Tutorial 4 – Time Test


The “Time Test” means if an unit test takes longer than the specified number of milliseconds to run, the test will terminated and mark as failed.
import org.testng.annotations.*;

/**
 * TestNG TimeOut Test
 * @author mkyong
 *
 */
public class TestNGTest4 {

    @Test(
timeOut = 1000 
    public void infinity() {  
        while (true);  
    }  

}
In above example, the infinity() method will not return, so the TestNG engine will mark it as failed and throw an exception
FAILED: infinity
org.testng.internal.thread.ThreadTimeoutException: 
Method public void TestNGTest4.infinity() didn't finish within the time-out 1000
... Removed 18 stack frames

TestNG Tutorial 5 – Suite Test


The “Suite Test” means bundle a few unit test cases and run it together.
In TestNG, XML file is use to define the suite test. The below XML file means both unit test “TestNGTest1” and “TestNGTest2” will execute together.


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
  <test name="testing">
    <classes>
       <class name="TestNGTest1" />
       <class name="TestNGTest2" />
    </classes>
  </test>
</suite>



Beside classes bundle testing, TestNG provides a “Grouping” feature to bundle few methods as a single unit for testing, where every method is tie to a group.
For example, Here’s a class with four methods, three groups (method1, method2 and method3)
import org.testng.annotations.*;

/**
 * TestNG Grouping
 * @author mkyong
 *
 */
public class TestNGTest5_2_0 {

    @Test(
groups="method1")
    public void testingMethod1() {  
      System.out.println("Method - testingMethod1()");
    }  

    @Test(groups="method2")
    public void testingMethod2() {  
        System.out.println("Method - testingMethod2()");
    }  

    @Test(groups="method1")
    public void testingMethod1_1() {  
        System.out.println("Method - testingMethod1_1()");
    }  

    @Test(groups="method4")
    public void testingMethod4() {  
        System.out.println("Method - testingMethod4()");
    }    
}
You can execute the unit test with group “method1” only.


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
  <test name="testing">
      <groups>
      <run>
        <include name="method1"/>
      </run>
    </groups>
    <classes>
       <class name="TestNGTest5_2_0" />
    </classes>
  </test>
</suite>




TestNG Tutorial 6 – Parameterized Test

The “Parameterized Test” means vary parameter value for unit test.

In TestNG, 
      
       XML file or 
       @DataProvider” 

is used to provide vary parameter for unit testing.


1. XML file for parameterized test.

Declare “@Parameters” annotation in method which needs parameter testing, the parametric data will be provide by TestNG’s XML configuration files. By doing this, you can reuse a single test case with different data sets easily. In addition, even end user, QA or QE can provide their own data sets for testing.
import org.testng.annotations.*;

/**
 * TestNG Parameterized Test
 * @author mkyong
 *
 */
public class TestNGTest6_1_0 {

    @Test
 
   @Parameters(value="number")
    public void parameterIntTest(int number) {
       System.out.println("Parameterized Number is : " + number);
    }
}


<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="My test suite">
  <test name="testing">

  
  <parameter name="number" value="2"/>     

    <classes>
       <class name="TestNGTest6_1_0" />
    </classes>
  </test>
</suite>





2. @DataProvider for parameterized test.

While pulling data values into an XML file can be quite handy, but test cases occasionally may require complex data types, which can’t be represented as a String or a primitive value in XML file. TestNG handles this scenario with@DataProvider annotation, which facilitates the mapping of complex parameter types to a test method.

1. @DataProvider for Vector, String or Integer as parameter

import java.util.Vector;
import org.testng.annotations.*;

/**
 * TestNG Parameterized Test - Advance
 * @author mkyong
 *
 */
public class TestNGTest6_2 {


    @Test(dataProvider = "Data-Provider-Function")
    public void parameterIntTest(Class clzz, String[] number) {
       System.out.println("Parameterized Number is : " + number[0]);
       System.out.println("Parameterized Number is : " + number[1]);
    }

    //This function will provide the parameter data
    @DataProvider(name = "Data-Provider-Function")
    public Object[][] parameterIntTestProvider() {
        return new Object[][]{
           {Vector.class, new String[] {"java.util.AbstractList", 
                                                 "java.util.AbstractCollection"}},
           {String.class, new String[] {"1", "2"}},
           {Integer.class, new String[] {"1", "2"}}
           };
    }
}
Result
Parameterized Number is : java.util.AbstractList
Parameterized Number is : java.util.AbstractCollection
Parameterized Number is : 1
Parameterized Number is : 2
Parameterized Number is : 1
Parameterized Number is : 2
PASSED: parameterIntTest(class java.util.Vector, [Ljava.lang.String;@1016632)
PASSED: parameterIntTest(class java.lang.String, [Ljava.lang.String;@10a6ae2)
PASSED: parameterIntTest(class java.lang.Integer, [Ljava.lang.String;@4a6cbf)



2. @DataProvider for object as parameter

“TestNGTest6_3_0” is a simple object with simple get set methods.
/**
 * TestNG Parameterized Test - Advance
 * @author mkyong
 *
 */
public class TestNGTest6_3_0 {

    private int number;
    private String msg;

    public void setNumber(int number){
        this.number = number;
    }

    public int getNumber(){
        return this.number;
    }

    public void setMsg(String msg){
        this.msg = msg;
    }

    public String getMsg(){
        return this.msg;
    }

}
import org.testng.annotations.*;

/**
 * TestNG Parameterized Test - Advance
 * @author mkyong
 *
 */
public class TestNGTest6_3_1 {

    @Test(dataProvider = "Data-Provider-Function")
    public void parameterIntTest(TestNGTest6_3_0 clzz) {
       System.out.println("Parameterized Number is : " + clzz.getMsg());
       System.out.println("Parameterized Number is : " + clzz.getNumber());
    }

    //This function will provide the patameter data
    @DataProvider(name = "Data-Provider-Function")
    public Object[][] parameterIntTestProvider() {

        TestNGTest6_3_0 obj = new TestNGTest6_3_0();
        obj.setMsg("Hello");
        obj.setNumber(123);

        return new Object[][]{
            {obj}
        };
    }    
}
Result
Parameterized Number is : 123
PASSED: parameterIntTest(TestNGTest6_3_0@dc6a77)
TestNG’s Parameterized test is very user friendly and flexible (either in XML file or inside the class). It can support many complex data type as parameter value and the possibility is unlimited. As example above, you even can pass in your own object (TestNGTest6_3_0) for Parameterized test.


TestNG parameter testing example
Published: December 1, 2009 , Updated: April 1, 2010 , Author: mkyong
print
TestNG parameter testing example.
Problem
Let’s say, a utility class has a function for converting the character to ASCII or vice verse, how can you test it with TestNG?
Solution
You can create a unit test function which accept two parameters (character and expected ASCII) from TestNG data provider, and assert the value like following :
Example in Java
package com.mkyong.common;
/**
 * Character Utility class
 * @author mkyong
 *
 */
public class CharUtils 
{   
    /**
     * Convert the characters to ASCII value
     * @param character character
     * @return ASCII value
     */
    public static int CharToASCII(final char character){
        return (int)character;
    }

    /**
     * Convert the ASCII value to character
     * @param ascii ascii value
     * @return character value
     */
    public static char ASCIIToChar(final int ascii){
        return (char)ascii;        
    }
}
Unit Test
package com.mkyong.common;
import org.testng.Assert;
import org.testng.annotations.*;
/**
 * Character Utils Testing
 * @author mkyong
 *
 */
public class CharUtilsTest {

    @DataProvider
    public Object[][] ValidDataProvider() {
        return new Object[][]{
                { 'A', 65 },{ 'a', 97 },
                { 'B', 66 },{ 'b', 98 },
                { 'C', 67 },{ 'c', 99 },
                { 'D', 68 },{ 'd', 100 },
                { 'Z', 90 },{ 'z', 122 },
                { '1', 49 },{ '9', 57 },

        };
    }

    @Test(dataProvider = "ValidDataProvider")
    public void CharToASCIITest(final char character, final int ascii) {
           int result = CharUtils.CharToASCII(character); 
           Assert.assertEquals(result, ascii);
    }

    @Test(dataProvider = "ValidDataProvider")
    public void ASCIIToCharTest(final char character, final int ascii) {
           char result = CharUtils.ASCIIToChar(ascii); 
           Assert.assertEquals(result, character); 
    }
}
Result
PASSED: CharToASCIITest(A, 65)
PASSED: CharToASCIITest(a, 97)
PASSED: CharToASCIITest(B, 66)
PASSED: CharToASCIITest(b, 98)
PASSED: CharToASCIITest(C, 67)
PASSED: CharToASCIITest(c, 99)
PASSED: CharToASCIITest(D, 68)
PASSED: CharToASCIITest(d, 100)
PASSED: CharToASCIITest(Z, 90)
PASSED: CharToASCIITest(z, 122)
PASSED: CharToASCIITest(1, 49)
PASSED: CharToASCIITest(9, 57)
PASSED: ASCIIToCharTest(A, 65)
PASSED: ASCIIToCharTest(a, 97)
PASSED: ASCIIToCharTest(B, 66)
PASSED: ASCIIToCharTest(b, 98)
PASSED: ASCIIToCharTest(C, 67)
PASSED: ASCIIToCharTest(c, 99)
PASSED: ASCIIToCharTest(D, 68)
PASSED: ASCIIToCharTest(d, 100)
PASSED: ASCIIToCharTest(Z, 90)
PASSED: ASCIIToCharTest(z, 122)
PASSED: ASCIIToCharTest(1, 49)
PASSED: ASCIIToCharTest(9, 57)

===============================================
    com.mkyong.common.CharUtilsTest
    Tests run: 24, Failures: 0, Skips: 0
===============================================


===============================================
mkyong
Total tests run: 24, Failures: 0, Skips: 0
===============================================



TestNG Tutorial 7 – Dependency Test
Published: May 16, 2009 , Updated: April 1, 2010 , Author: mkyong
print
The “Dependency Test” means methods are test base on dependency. If the dependent method fails, all the subsequent test methods will be skipped, not marked as failed.
TestNG uses “dependOnMethods“ to implement the dependency testing as following
import org.testng.annotations.*;

/**
 * TestNG Dependency Test
 * @author mkyong
 *
 */
public class TestNGTest7 {

    @Test
    public void method1() {
       System.out.println("This is method 1");
    }

    @Test(dependsOnMethods={"method1"})
    public void method2() {
        System.out.println("This is method 2");
    }


}
Result
PASSED: method1
PASSED: method2
The “method2()” will execute only if “method1()” is run successfully, else “method2()” will skip.


Q: What is your framework?
Ans :
•    I am using Hybrid Framework.
•     Framework contains Application specific components and application independent components.
•    Application independent components are like
o    Various actions on webpage :
§    Click
§    Getattribute
§    Gettext
§    Elementpresent
§    Elementvisible
§    Waitforelementtopresent
§    Getvalue
§    Getselectedoption from List
§    Switchwindow
§    Movemouseon
§    Radiobutton selection
§    Selectbyvalue
§    Textbox
§    Textboxpresent
o    Basically to deal with Links, textboxes, List, verifytext, closepopup, database connection, common database queries to fetch test data



Note : browserpagefactory : Singleton : http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html

  Q : How does your testdata managed in your framework ?
  Ans : We are using Spring Framework for managing testdata.
            The lowest level implementation of the IoC container is the BeanFactory, but it is recommended to use an ApplicationContext for your application. The ApplicationContext is a subclass of the BeanFactory interface so it has all the functionality a BeanFactory has and more. Unless you are writing an application that needs an extremely small memory footprint, BeanFactory shouldn't be used directly.
There are a few different ApplicationContext implementations that can be used, which can be learned about by reading the Spring Framework's documentation and source code. For the purposes of this example, we'll use a very popular one –ClassPathXmlApplicationContext, which defaults to reading resources from the classpath. If you need to use a different location for your classes, you can append prefixes before the configuration file's path such as 'file', 'http', etc. This will force the ApplicationContext to read from somewhere other than the default location.
private static ApplicationContext applicationContext = new ClassPathXmlApplicationContext(getLocations());

private static String[] getLocations() {
        if (System.getProperty("app.env") == null) {
            System.err.println("[WARNING] No APPLICATION ENVIRONMENT SET in 'app.env'. Using 'default'");
            System.setProperty("app.env", "default");
        }
        return new String[] {
                "/applicationContext-storetest.test.xml"
        };
    }
// The common properties bean
    private static CommonPropertiesBean cp = (CommonPropertiesBean) applicationContext.getBean("commonProperties");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!--
        This bean points spring to the config file, change value to point to a
        new config file
    -->
    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="test.${app.env}.properties" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
    </bean>

    <!--
        This bean is the datasource bean, this is what you will use to inject
        the Database object
    -->
    <bean id="storeTestDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="storeLocatorTestDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${sl.jdbc.url}" />
        <property name="username" value="${sl.jdbc.username}" />
        <property name="password" value="${sl.jdbc.password}" />
    </bean>

    <bean id="storeLocatorServiceTestDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${storelocator.jdbc.url}" />
        <property name="username" value="${storelocator.jdbc.username}" />
        <property name="password" value="${storelocator.jdbc.password}" />
    </bean>

    <bean id="jdaTestDataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jda.jdbc.driverClassName}" />
        <property name="url" value="${jda.jdbc.url}" />
        <property name="username" value="${jda.jdbc.username}" />
        <property name="password" value="${jda.jdbc.password}" />
    </bean>
   
    <bean id="PaypalPropertiesBean" class="com.gsicommerce.webstore.utilities.PaypalPropertiesBean">
        <property name="paypalURL" value="${paypal.url}" />
        <property name="paypalMainUser" value="${paypal.main.user}" />
        <property name="paypalMainPass" value="${paypal.main.pass}" />
        <property name="paypalTestUser" value="${paypal.test.user}" />
        <property name="paypalTestPass" value="${paypal.test.pass}" />
    </bean>
   
    <!--
        This bean is the CommonPropertiesBean, it holds the browser
        information for webdriver tests
    -->
    <bean id="commonProperties" class="com.gsicommerce.webstore.utilities.CommonPropertiesBean">
        <property name="storeCode" value="${store.code}" />
        <property name="storeLocale" value="${store.locale}" />
        <property name="countryCode" value="${store.countryCode}" />
        <property name="currencyCode" value="${store.currencyCode}" />
        <property name="productUpdate" value="${product.update}" />
        <property name="storeEnvironment" value="${store.environment}" />
        <property name="browserType" value="${browser.type}" />
        <property name="appURL" value="${app.url}" />
        <property name="rtURL" value="${rt.url}" />
        <property name="cacheURL" value="${cache.url}" />
        <property name="remoteBrowserUrl" value="${remote.browser.url}" />
        <property name="catmanURL" value="${catman.url}" />
        <property name="catmanUsername" value="${catman.username}" ></property>
        <property name="catmanPassword" value="${catman.password}" />
        <property name="firefoxProfile" value="${firefox.profile}" />
        <property name="browserVersion" value="${browser.version}" />
        <property name="browserCapture" value="${browser.capture}" />
        <property name="remoteToolsUsername" value="${rt.username}" />
        <property name="remoteToolsPassword" value="${rt.password}" />
        <property name="storeLocatorURL" value="${storeLocator.url}" />
        <property name="testUserName" value="${test.user.name}" />
        <property name="testUserPassword" value="${test.user.password}" />
        <property name="epiphanyURL" value="${epiphany.url}" />
        <property name="epiphanyUsername" value="${epiphany.username}" />
        <property name="epiphanyPassword" value="${epiphany.password}" />
        <property name="jdaSystem" value="${jda.system}" />
        <property name="jdaUsername" value="${jda.username}" />
        <property name="jdaPassword" value="${jda.password}" />
        <property name="storeLocatorServiceClearCacheUrl" value="${storeLocatorService.clearCache.url}"/>
    </bean>
</beans>

----------------------------------------------------------------------------

public static String storeCode = cp.getStoreCode();








Q1. What is Selenium?
Ans. Selenium is a set of tools that supports rapid development of test automation scripts for web
based applications. Selenium testing tools provides a rich set of testing functions specifically
designed to fulfil needs of testing of a web based application.

Q2. What are the main components of Selenium testing tools?
Ans. Selenium IDE, Selenium RC and Selenium Grid

Q3. What is Selenium IDE?
Ans. Selenium IDE is for building Selenium test cases. It operates as a Mozilla Firefox add on and
provides an easy to use interface for developing and running individual test cases or entire test
suites. Selenium-IDE has a recording feature, which will keep account of user actions as they are
performed and store them as a reusable script to play back.

Q4. What is the use of context menu in Selenium IDE?
Ans. It allows the user to pick from a list of assertions and verifications for the selected location.

Q5. Can tests recorded using Selenium IDE be run in other browsers?
Ans. Yes. Although Selenium IDE is a Firefox add on, however, tests created in it can also be run in
other browsers by using Selenium RC (Selenium Remote Control) and specifying the name of the test
suite in command line.

Q6. What are the advantage and features of Selenium IDE?
Ans. 1. Intelligent field selection will use IDs, names, or XPath as needed
2. It is a record & playback tool and the script format can be written in various languages including
C#, Java, PERL, Python, PHP, HTML
3. Auto complete for all common Selenium commands
4. Debug and set breakpoints
5. Option to automatically assert the title of every page
6. Support for Selenium user-extensions.js file

Q7. What are the disadvantage of Selenium IDE tool?
Ans. 1. Selenium IDE tool can only be used in Mozilla Firefox browser.
2. It is not playing multiple windows when we record it.

Q8. What is Selenium RC (Remote Control)?
Ans. Selenium RC allows the test automation expert to use a programming language for maximum
flexibility and extensibility in developing test logic. For example, if the application under test returns
a result set and the automated test program needs to run tests on each element in the result set, the
iteration / loop support of programming language’s can be used to iterate through the result set,
calling Selenium commands to run tests on each item.

Selenium RC provides an API and library for each of its supported languages. This ability to use
Selenium RC with a high level programming language to develop test cases also allows the automated
testing to be integrated with the project’s automated build environment.

Q9. What is Selenium Grid?
Ans. Selenium Grid in the selenium testing suit allows the Selenium RC solution to scale for test suites
that must be run in multiple environments. Selenium Grid can be used to run multiple instances of
Selenium RC on various operating system and browser configurations.

Q10. How Selenium Grid works?
Ans. Selenium Grid sent the tests to the hub. Then tests are redirected to an available Selenium RC,
which launch the browser and run the test. Thus, it allows for running tests in parallel with the entire
test suite.

Q 11. What you say about the flexibility of Selenium test suite?
Ans. Selenium testing suite is highly flexible. There are multiple ways to add functionality to Selenium
framework to customize test automation. As compared to other test automation tools, it is
Selenium’s strongest characteristic. Selenium Remote Control support for multiple programming and
scripting languages allows the test automation engineer to build any logic they need into their
automated testing and to use a preferred programming or scripting language of one’s choice.
Also, the Selenium testing suite is an open source project where code can be modified and
enhancements can be submitted for contribution.

Q12. What test can Selenium do?
Ans. Selenium is basically used for the functional testing of web based applications. It can be used for
testing in the continuous integration environment. It is also useful for agile testing

Q13. What is the cost of Selenium test suite?
Ans. Selenium test suite a set of open source software tool, it is free of cost.

Q14. What browsers are supported by Selenium Remote Control?
Ans. The test automation expert can use Firefox, IE 7/8, Safari and Opera browsers to run tests in
Selenium Remote Control.

Q15. What programming languages can you use in Selenium RC?
Ans. C#, Java, Perl, PHP, Python, Ruby

Q16. What are the advantages and disadvantages of using Selenium as testing tool?
Ans. Advantages: Free, Simple and powerful DOM (document object model) level testing, can be used
for continuous integration; great fit with Agile projects.

Disadvantages: Tricky setup; dreary errors diagnosis; can not test client server applications.

Q17. What is difference between QTP and Selenium?
Ans. Only web applications can be testing using Selenium testing suite. However, QTP can be used for
testing client server applications. Selenium supports following web browsers: Internet Explorer,
Firefox, Safari, Opera or Konqueror on Windows, Mac OS X and Linux. However, QTP is limited to
Internet Explorer on Windows.

QTP uses scripting language implemented on top of VB Script. However, Selenium test suite has the
flexibility to use many languages like Java, .Net, Perl, PHP, Python, and Ruby.

Q18. What is difference between Borland Silk test and Selenium?
Ans. Selenium is completely free test automation tool, while Silk Test is not. Only web applications
can be testing using Selenium testing suite. However, Silk Test can be used for testing client server
applications. Selenium supports following web browsers: Internet Explorer, Firefox, Safari, Opera or
Konqueror on Windows, Mac OS X and Linux. However, Silk Test is limited to Internet Explorer and
Firefox.

Silk Test uses 4Test scripting language. However, Selenium test suite has the flexibility to use many
languages like Java, .Net, Perl, PHP, Python, and Ruby.

What is Selenium?
Selenium is a suite of tools for browser automation. It is composed of "IDE", a recording and playback mechanism, "WebDriver" and "RC" which provide APIs for browser automation in a wide variety of languages, and "Grid", which allows many tests using the APIs to be run in parallel. It works with most browsers, including Firefox from 3.0 up to 7, Internet Explorer 8, Google Chrome, Safari and Opera 11.5
•    Describe technical problems that you had with Selenium tool?
As with any other type of test automation tools like SilkTest, HP QTP, Watir, Canoo Webtest, Selenium allows to record, edit, and debug tests cases. However there are several problems that seriously affect maintainability of recorded test cases, occasionally Quality Assurance Engineers complain that it takes more time to maintain automated test cases than to perform manual testing; however this is an issue with all automated testing tools and most likely related to improper testing framework design. Another problem is complex ID for an HTML element. If IDs is auto-generated, the recorder test cases may fail during playback. The work around is to use XPath to find required HTML element. Selenium supports AJAX without problems, but QA Tester should be aware that Selenium does not know when AJAX action is completed, so ClickAndWait will not work. Instead QA tester could use pause, but the snowballing effect of several 'pause' commands would really slow down total testing time of test cases. The best solution would be to use waitForElement.
•    What test can Selenium do?
Selenium could be used for the functional, regression, load testing of the web based applications. The automation tool could be implemented for post release validation with continuous integration tools like Jenkins, Hudson, QuickBuild or CruiseControl.
•    What is the price of Selenium license per server?
Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without charge.
•    How much does Selenium license cost per client machine?
Selenium is open source software, released under the Apache 2.0 license and can be downloaded and used without charge.
•    Where to download Selenium?
Selenium can be downloaded and installed for free from seleniumhq.org
•    What is the latest version of Selenium components?
The latest versions are Selenium IDE 1.3.0, Selenium Server (formerly the Selenium RC Server) 2.9.0, Selenium Client Drivers Java 2.9.0, Selenium Client Drivers C# 2.9.0, Selenium Client Drivers Ruby 2.8.0, Selenium Client Drivers Python 2.9, Selenium Grid 1.0.8.
•    What is Selenium IDE?
Selenium IDE is a Firefox add-on that records clicks, typing, and other actions to make a test cases, which QA Tester can play back in the Firefox browser or export to Selenium RC. Selenium IDE has the following features: record/play feature, debugging with step-by-step and breakpoints, page abstraction functionality, an extensibility capability allowing the use of add-ons or user extensions that expand the functionality of Selenium IDE


•    What are the limitations of Selenium IDE?
Selenium IDE has many great features and is a fruitful and well-organized test automation tool for developing test cases, in the same time Selenium IDE is missing certain vital features of a testing tool: conditional statements, loops, logging functionality, exception handling, reporting functionality, database testing, re-execution of failed tests and screenshots taking capability. Selenium IDE doesn't for IE, Safari and Opera browsers.
What does SIDE stand for?
Selenium IDE. It was a very tricky interview question.
•    What is Selenium Remote Control (RC) tool?
Selenium Remote Control (RC) is the powerful solution for test cases that need more than simple browser actions and linear execution. Selenium-RC allows the developing of complex test scenarios like reading and writing files, querying a database, and emailing test reports. These tasks can be achieved by tweaking test cases in your preferred programming language.
•    What are the advantages using Selenium as testing tool?
If QA Tester would compare Selenium with HP QTP or Micro Focus SilkTest, QA Engineer would easily notice tremendous cost savings for Selenium. In contrast to expensive SilkTest license or QTP license, Selenium automation tool is absolutely free. It means that with almost no investment in purchasing tools, QA Team could easily build the state of the art test automation infrastructure. Selenium allows developing and executing test cases in various programming languages including .NET, Java, Perl, RubyPython, PHP and even HTML. This is a great Selenium advantage, most likely your software developers already know how to develop and maintain C# or Java code, so they transfer coding techniques and best practices to QA team. Selenium allows simple and powerful DOM-level testing and in the same time could be used for testing in the traditional waterfall or modern Agile environments. Selenium would be definitely a great fit for the continuous integration tools Jenkins, Hudson, CruiseControl, because it could be installed on the server testing box, and controlled remotely from continuous integration build.

•    What is Selenium Grid?
Selenium Grid extends Selenium RC to distribute your tests across multiple servers, saving you time by running tests in parallel.
•    What is Selenium WebDriver?
Selenium WebDriver is a tool for writing automated tests of websites. It is an API name and aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application. Selenium WebDriver is the successor of Selenium Remote Control which has been officially deprecated.
•    How many browsers are supported by Selenium IDE?
Test Engineer can record and playback test with Selenium IDE in Firefox.
•    Can Selenium test an application on iPhone's Mobile Safari browser?
Selenium should be able to handle Mobile Safari browser. There is experimental Selenium IPhone Driver for running tests on Mobile Safari on the iPhone, iPad and iPod Touch.
•    Can Selenium test an application on Android browser?
Selenium should be able to handle Android browser. There is experimental Selenium Android Driver for running tests in Android browser.
•    What are the disadvantages of using Selenium as testing tool?
Selenium weak points are tricky setup; dreary errors diagnosis; tests only web applications
•    How many browsers are supported by Selenium Remote Control?
QA Engineer can use Firefox 7, IE 8, Safari 5 and Opera 11.5 browsers to run actuall tests in Selenium RC.
•    How many programming languages can you use in Selenium RC?
Several programming languages are supported by Selenium Remote Control - C# Java Perl PHP Python Ruby
•    How many testing framework can QA Tester use in Selenium RC?
Testing frameworks aren't required, but they can be helpful if QA Tester wants to automate test cases. Selenium RC supports Bromine, JUnit, NUnit, RSpec (Ruby), Test::Unit (Ruby), TestNG (Java), unittest (Python).
•    How to developer Selenium Test Cases?
Using the Selenium IDE, QA Tester can record a test to comprehend the syntax of Selenium IDE commands, or to check the basic syntax for a specific type of user interface. Keep in mind that Selenium IDE recorder is not clever as QA Testers want it to be. Quality assurance team should never consider Selenium IDE as a "record, save, and run it" tool, all the time anticipate reworking a recorded test cases to make them maintainable in the future.
•    What programming language is best for writing Selenium tests?
The web applications may be written in Java, Ruby, PHP, Python or any other web framework. There are certain advantages for using the same language for writing test cases as application under test. For example, if the team already have the experience with Java, QA Tester could always get the piece of advice while mastering Selenium test cases in Java. Sometimes it is better to choose simpler programming language that will ultimately deliver better success. In this case QA testers can adopt easier programming languages, for example Ruby, much faster comparing with Java, and can become become experts as soon as possible.
•    Have you read any good books on Selenium?
There are several great books covering Selenium automation tool, you could check the review at Best Selenium Books: Top Recommended page
•    Do you know any alternative test automation tools for Selenium?
Selenium appears to be the mainstream open source tool for browser side testing, but there are many alternatives. Canoo Webtest is a great Selenium alternative and it is probably the fastest automation tool. Another Selenium alternative is Watir, but in order to use Watir QA Tester has to learn Ruby. One more alternative to Selenium is Sahi, but is has confusing interface and small developers community.
•    Compare HP QTP vs Selenium?
When QA team considers acquiring test automation to assist in testing, one of the most critical decisions is what technologies or tools to use to automate the testing. The most obvious approach will be to look to the software market and evaluate a few test automation tools. Read Selenium vs QTP comparison
•    Compare Borland Silktest vs Selenium?
Check Selenium vs SilkTest comparison
•    How to test Ajax application with Selenium
Ajax interview questions could be tough for newbie in the test automation, but will be easily cracked by Selenium Tester with a relevant experience. Read the detailed approach at Testing Ajax applications with Selenium in the right way
•    How can I learn to automate testing using Selenium?
Don't be surprised if the interviewer asks you to describe the approach for learning Selenium. This interviewer wants to hear how you can innovative software test automation process the company. Most likely they are looking for software professional with a good Selenium experience, who can do Selenium training for team members and get the team started with test automation. I hope this Selenium tutorial will be helpful in the preparation for this Selenium interview question.
1. What do you know about Selenium?

Selenium is a suite of tools for web automation testing.
Selenium first came to life in 2004 when Jason Huggins was testing an internal application at ThoughtWorks.
Selenium was a tremendous tool, it wasn’t without it’s drawbacks. Because of its Javascript based automation engine and the security limitations browsers apply to Javascript, different things became impossible to do.
Selenium Suite of projects include:
Selenium IDE
Selenium Core
Selenium 1 (known as. Selenium RC or Remote Control)
Selenium 2 (known as. Selenium Webdriver)
Selenium-Grid

2. What are the technical challenges with selenium?
View
As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.
1. Selenium Supports only web based applications
2. It doesn’t support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications
3. When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability of the test cases
4. Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications
5. There is no object repository concept in Selenium, so maintainability of the objects is very high
6. There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applications
7. Bitmap comparison is not supported by Selenium
8. Any reporting related capabilities, you need to depend on third party tools
9. You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scripting side of selenium

3. What are the test types supported by Selenium?
Selenium could be used for testing the web based applications. The test types can be supported are:
1. functional,
2. regression,
3. load testing
The automation tool could be implemented for post release validation with continuous integration tools like:
1. Jenkins,
2. Hudson,
3. QuickBuild
4. CruiseCont

4. What are the capabilities of Selenium IDE?
Selenium IDE (Integrated Development Environment) works similar to commercial tools like QTP, Silk Test and Test Partner etc. The below mentioned points describes well about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other actions to make a test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. Debugging of the test cases with step-by-step can be done
6. breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can supports an extensibility capability allowing the use of add-ons or user extensions that expand the functionality of Selenium IDE
4. What are the capabilities of Selenium IDE?
Selenium IDE (Integrated Development Environment) works similar to commercial tools like QTP, Silk Test and Test Partner etc. The below mentioned points describes well about Selenium IDE.
1. Selenium IDE is a Firefox add-on.
2. Selenium IDE can support recording the clicks, typing, and other actions to make a test cases.
3. Using Selenium IDE A Tester can play back the test cases in the Firefox browser
4. Selenium IDE supports exporting the test cases and suites to Selenium RC.
5. Debugging of the test cases with step-by-step can be done
6. breakpoint insertion is possible
7. Page abstraction functionality is supported by Selenium IDE
8. Selenium IDE can supports an extensibility capability allowing the use of add-ons or user extensions that expand the functionality of Selenium IDE
6. Which are the browsers supported by Selenium IDE?
Selenium IDE supports only one browser Mozilla Firefox. The versions supported as of now are:
Mozilla Firefox 2.x
Mozilla Firefox 3.x
The versions not supported as of now are:
earlier versions of Mozilla Firefox 2.x
Mozilla Firefox 4.x
7. How to execute a single line command from Selenium IDE?
Single line command from Selenium IDE can be executed in two ways
1. Right click on the command in Selenium IDE and select "Execute This Command"
2. Select the command in Selenium IDE and press "X" key on the keyboard
8. How to insert a start point in Selenium IDE?
Start point Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Set / Clear Start Point"
2. Select the command in Selenium IDE and press "S" key on the keyboard
3. You can have only one start point
4. If you have already set one start point and you selected other command as start point. Then the first start point will be removed and the new start point will be set
1. Right click on the command in Selenium IDE and select "Inert New Comment"
2. If you want to comment an existing line. You need to follow the below mentioned steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>

9. How to insert a comment in Selenium IDE?
Comments in Selenium IDE can be set in two ways
1. Right click on the command in Selenium IDE and select "Inert New Comment"
2. If you want to comment an existing line. You need to follow the below mentioned steps.
a. Select the source tab in IDE
b. Select the line which you want to comment
c. Assume that if you want to comment a open command you need to write like below mentioned code
<tr>
<!--
<td>open&l/td>
<td>/node/304/edit&l/td>
<td></td>
-->
</tr>

10. How to insert a break point in Selenium IDE?
Break point can be set in two ways in Selenium IDE
1. Right click on the command in Selenium IDE and select "Toggle Break Point"
2. Select the command in Selenium IDE and press "B" key on the keyboard
3. If you want to clear the break point once again Spress "B" key on the keyboard
4. You can set multiple break points in Selenium IDE
11. How to debug the tests in Selenium IDE?
To debug or execute the test cases line by line. Follow the below mentioned steps
1. Insert a break point (see the question to know more How to insert a break point in Selenium IDE? )from the location where you want to execute step by step
2. Run the test case
3. execution will be paused at the given break point
4. Click on the step (Blue) button to continue with the next statement
5. Click on Run button, to continue executing all the commands at a time
12. How to export the tests from Selenium IDE to Selenium RC in different languages?
From selenium IDE the test cases can be exported into the languages
1. .Net,
2. Java,
3. Perl,
4. Python,
5. PHP,
6. Ruby
The below mentioned steps can explain how to export the test cases
1. Open the test case from Selenium IDE
2. Select File -> Export Test Case As
13. How to export Selenium IDE Test Suite to Selenium RC Suites?
From selenium IDE the test suites can be exported into the languages as mentioned below
1. .Net,
2. Java,
3. Perl,
4. Python,
5. PHP,
6. Ruby
The below mentioned steps can explain how to export the test suites
1. Open the test case from Selenium IDE
2. Select File -> Export Test Suite As
14. Which is the command used for displaying the values of a variable into the output console or log?
The command used for displaying the values of a variable into the output console or log - echo
If you want to display a constant string. The below mentioned command can be used
echo <constant string>
ex: echo "The sample message"
If you want to display the value of a variable it can be written like below
echo ${<variable name>>
ex: echo ${var1}
Note: Here var1 is the variable
15. Which are the browsers supported by Selenium RC?
Supported browsers for Selenium RC include:
1. *firefox
2. *mock
3. *firefoxproxy
4. *pifirefox
5. *chrome
6. *iexploreproxy
7. *iexplore
8. *firefox3
9. *safariproxy
10. *googlechrome
11. *konqueror
12. *firefox2
13. *safari
14. *piiexplore
15. *firefoxchrome
16. *opera
17. *iehta
18. *custom
Note: Any third party browser is supported with *custom followed by the complete path of the browser with executable
16. Which are the Operating Systems supported by Selenium?
Selenium IDE
Works in Firefox 2+ Start browser, run tests Run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others whichever supports Firefox 2+
Selenium Remote Control
Used for starting browser and run tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
Selenium Core
Used for running tests
Operating Systems Supported:
1. Windows,
2. OS X
3. Linux
4. Solaris
5. Others
17. What is Selenium RC?
View
Selenium-RC is the solution for tests that need a little more than just simple browser actions and a linear execution. Selenium-RC leverages the full power of programming languages, creating tests that can do things like read and write external files, make queries to a database, send emails with test reports, and practically anything else a user can do with a normal application.
You will want to use Selenium-RC whenever your test requires logic not supported by running a script from Selenium-IDE

18. Why Selenium RC is used?
Selenium-IDE does not directly support:
1. condition statements
2. iteration
3. logging and reporting of test results
4. error handling, particularly unexpected errors
5. database testing
6. test case grouping
7. re-execution of failed tests
8. test case dependency
9. capture screenshots on test failures
The reason behind why Selenium-IDE does not support the above mentioned requirements is IDE supports only HTML language. Using HTML language we cannot achieve the above mentioned requirements. Because HTML does not support conditional, looping and external source connectives.
To overcome the above mentioned problems Selenium RC is used.
Since Selenium RC supports the languages .Net, Java, Perl, Python, PHP, and Ruby. In these languages we can write the programme to achieve the IDE issues


19. Which are the languages supported by Selenium RC?
View
The languages supported by Selenium RC
1. .Net,
2. Java (Junt 3, Junt 4, TestNG, Groovy)
3. Perl,
4. Python,
5. PHP,
6. Ruby
20. What is Selenium Grid?
View
Selenium Grid is part of Selenium suite of projects. Selenium Grid transparently distribute your tests on multiple machines so that you can run your tests in parallel, cutting down the time required for running in-browser test suites. This will dramatically speeds up in-browser web testing, giving you quick and accurate feedback you can rely on to improve your web application.

21. What is Selenium WebDriver or Google WebDriver or Selenium 2.0?
View
WebDriver uses a different underlying framework from Selenium’s javascript Selenium-Core. It also provides an alternative API with functionality not supported in Selenium-RC. WebDriver does not depend on a javascript core embedded within the browser, therefore it is able to avoid some long-running Selenium limitations.
WebDriver’s goal is to provide an API that establishes
• A well-designed standard programming interface for web-app testing.
• Improved consistency between browsers.
• Additional functionality addressing testing problems not well-supported in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating WebDriver is another step in that process. The developers of Selenium and of WebDriver felt they could make significant gains for the Open Source testautomation community be combining forces and merging their ideas and technologies. Integrating WebDriver intoSelenium is the current result of those efforts.

22. What are the capabilities of Selenium WebDriver or Google WebDriver or Selenium 2.0?
One should use WebDriver when requiring improved support for
• Mult-browser testing including improved functionality for browsers not well-supported by Selenium-1.0.
• Handling multiple frames, multiple browser windows, popups, and alerts.
• Page navigation.
• Drag-and-drop.
• AJAX-based UI elements.
nderlying framework from Selenium’s javascript Selenium-Core. It also provides an alternative API with functionality not supported in Selenium-RC. WebDriver does not depend on a javascript core embedded within the browser, therefore it is able to avoid some long-running Selenium limitations.
WebDriver’s goal is to provide an API that establishes
• A well-designed standard programming interface for web-app testing.
• Improved consistency between browsers.
• Additional functionality addressing testing problems not well-supported in Selenium 1.0.
The Selenium developers strive to continuously improve Selenium. Integrating WebDriver is another step in that process. The developers of Selenium and of WebDriver felt they could make significant gains for the Open Source testautomation community be combining forces and merging their ideas and technologies. Integrating WebDriver intoSelenium is the current result of those efforts.
24. What is the architecture of Selenium Grid?
The below mentioned theory explains about the setup of Selenium Grid with architecture and how it works.
Selenium Grid builds on the traditional Selenium setup, taking advantage of the following properties:
* The Selenium test, the application under test, and the remote control/browser pair do not have to be co-located. They communicate through HTTP, so they can all live on different machines.
* The Selenium tests and the web application under test are obviously specific to a particular project. Nevertheless, neither the Selenium remote control nor the browser is tied to a specific application. As a matter of fact, they provide a capacity that can easily be shared by multiple applications and multiple projects.
Consequently, if only we could build a distributed grid of Selenium Remote Controls, we could easily share it across builds, applications, projects - even potentially across organizations. Of course we would also need to address the scalability issues as described earlier when covering the traditional Selenium setup. This is why we need a component in charge of:
* Allocating a Selenium Remote Control to a specific test (transparently)
* Limiting the number of concurrent test runs on each Remote Control
* Shielding the tests from the actual grid infrastructure
Selenium Grid calls this component the Selenium Hub.
* The Hub exposes an external interface that is exactly the same as the one of a traditional Remote Control. This means that a test suite can transparently target a regular Remote Control or a Selenium Hub with no code change. It just needs to target a different IP address. This is important as it shields the tests from the gridinfrastructure (which you can scale transparently). This also makes the developer’s life easier. The same test can be run locally on a developer machine, or run on a heavy duty distributed grid as part of a build – without ever changing a line of code.
* The Hub allocates Selenium Remote Controls to each test. The Hub is also in charge of routing the Selenese requests from the tests to the appropriate Remote Control as well as keeping track of testing sessions.
* When a new test starts, the Hub puts its first request on hold if there is no available Remote Control in the grid providing the appropriate capabilities. As soon as a suitable Remote Control becomes available, the Hub will serve the request. For the whole time, the tests do not have to be aware of what is happening within the grid; it is just waiting for an HTTP response to come back.
25. Does Selenium support mobile internet testing?
View
Selenium supports Opera. And opera is used in most of the Smart phones. So whichever Smart phone supports opera, selenium can be used to test. So, one can use Selenium RC to run the tests on mobiles.
For more details on supported browsers of Selenium Which are the browsers supported by Selenium RC?
26. Does Selenium support Google Android Operating System?
View
Yes, Selenium Web Driver or Google Web Driver or Selenium 2.0 supports Android Operating System. There are several libraries written to support Android Operating System.
Fri, 07/15/2011 - 04:35 — Visitor
selenium android driver testing
try this .... this is cool ... ;)
public class OneTest extends TestCase {
public void testGoogle() throws Exception {
AndroidDriver driver = new AndroidDriver();
// And now use this to visit Google
driver.get("http://google.com");
Thread.sleep(15000);
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("hotmail");
//driver.findElement(By.name("q")).sendKeys("niloy.cit");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
//driver.findElement(By.name("btnG")).click();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}

how i can give command to a already run webdriver to open an application or websight in emulator or real device ??


27. What are the types of text patterns available in Selenium?
There are three types of patterns available in Selenium
1. globbing
2. regular expressions
3. exact
28. How to use regular expressions in Selenium?
Regular expressions in Selenium IDE can be used with the keyword - regexp: as a prefix to the value and patterns needs to be included for the expected values.
For example if you want to use the regular expression for a command
Command: verifyText
Target: //font/font/b/font[1]
Value: Flight Confirmation # 2011-05-02451
in the above example Flight Confirmation is continuously changing each time you run the test case. So this can be written with a regular expression as mentioned below
Command: verifyText
Target: //font/font/b/font[1]
Value: regexp:Flight Confirmation # [0-9]{4}-[0-9]{2}-[0-9]{5,10}
29. What are the regular expression patterns available in Selenium?
Selenium regular expression patterns offer the same wide array of special characters that exist in JavaScript. Below are a subset of those special characters
PATTERN    MATCH
.    any single character
[ ]    character class: any single character that appears inside the brackets
*    quantifier: 0 or more of the preceding character (or group)
+    quantifier: 1 or more of the preceding character (or group)
?    quantifier: 0 or 1 of the preceding character (or group)
{1,5}    quantifier: 1 through 5 of the preceding character (or group)
|    alternation: the character/group on the left or the character/group on the right
( )    grouping: often used with alternation and/or quantifier


30. What is Selenese?
Selenium set of commands which are used for running the test are called as Selenese.
There are three types of Selenese, those are:
1. Actions - used for performing the operations and interactions with the target elements
2. Assertions - used as check points
3. Accessors - used for storing the values in a variable

31. How do you add check points or verification points in Selenium?
check points or verification points are known as Assertions in Selenium. The keywords with below mentioned prefix will be used for adding check points or verification points.
1. verify
2. assert
3. waitFor
32. What is Assertion in Selenium?
Assertion is nothing but a check or verification point.
Assertion verifies the state of the application conforms to what is expected.
Examples include “make sure the page title is X” and “verify that this checkbox is checked.
33. What are the types of Assertions there in Selenium?
Selenium Assertions can be used in 3 modes:
1) assert - When an “assert” fails, the test will be aborted. If you are executing test suite, the next state case will start
2) verify - When a “verify” fails, the test will continue execution, logging the failure.
3) waitFor - “waitFor” commands wait for some condition to become true (which can be useful for testing Ajaxapplications). They will succeed immediately if the condition is already true. However, they will fail and halt the test if the condition does not become true within the current timeout setting


34. When to use Assert, Verify and WaitFor in Selenium?
1) assert - If the expected value is mandatory to continue with the next set of steps we will use Assert. As Assert aborts the test, if the expected value doesn't match. It is good to use for any mandatory checks.
2) verify - If the expected value is optional to continue with the next set of steps we will use Verify. As Verify continues executing with the next set of steps, if the expected value doesn't match. It is good to use for any optional checks.
3) waitFor - If your test needs to wait, if the expected value is not matching we use waitFor. We normally use waitFor for AJAX kind of controls loading within a page


35. What is an Accessor in Selenium?
Accessor is one of the type of Selenese.
I. Accessors are used for storing the value of a target in a variable.
Ex:
1) storeTitle - Stores the title of a window in a variable
2) storeText - Stores the target element text in a variable
II. Accessors are also used for evaluating the result and storing the result in a variable
Ex: storeTextPresent - Evaluates whether the text is present in the current window. If the text is present stores true in the variable else stores false
Ex: storeEementPresent - Evaluates whether the element is present in the current window. If the element is present stores true in the variable else stores false
36. When to use Accessors in Selenium?
View
Accessors are mostly used for storing the value in a variable.
The variable can be used for following reasons:
1) To get the value from an element and comparing with some dynamic value
2) To take a logical decision to execute the test steps
ex: if the value of the variable true execute step1 and step2 else step3 and step4
3) To execute some statements in a loop based on the value returned by the element
37. How to capture bitmaps in Selenium?
View
Bitmaps are captured using the Selenium set of commands. There are two modes of capturing the bitmaps
1) Capture the bitmap for the entire page - it captures the browser main page area of AUT
2) Capture the bitmap for the screen shots - it captures the entire screen shot like the print scree that you give from your keyboard
Selenium doesn't support bitmap capturing for an element on AUT.
38. Which are the commands used for capturing the bitmaps?
captureEntirePageScreenshot
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see captureEntirePageScreenshot for more details
captureEntirePageScreenshotAndWait
Saves the entire contents of the current window canvas to a PNG file. Contrast this with the captureScreenshot command, which captures the contents of the OS viewport (i.e. whatever is currently being displayed on the monitor), and is implemented in the RC only. Currently this only works in Firefox when running in chrome mode, and in IE non-HTA using the EXPERIMENTAL "Snapsie" utility. The Firefox implementation is mostly borrowed from the Screengrab! Firefox extension. Please see
captureEntirePageScreenshotAndWait for details.
Note: This command runs with only mozilla firefox when you run the tests from RC. Other browsers it will not support
39. What is the difference between captureEntirePageScreenshot and CaptureScreenShot?
View
captureEntirePageScreenshot
1. This captures the AUT web page only
2. This supports only mozilla firefox
3. Accepts two arguments. one is the file name to be saved and other argument is back ground color
CaptureScreenShot
1. This captures the System screen shot
2. This supports all the browsers when you run from Selenium RC
3. Accepts one argument. That is the file name to be saved.


41. What are the limitations of Selenium IDE
View
The limitations of Selenium IDE are:
1) Selenium IDE uses only HTML language
2) Conditional or branching statements execution like using of if, select statements is not possible
3) Looping statements using is not possible directly in Selenium HTML language in ide
4) Reading from external files like .txt, .xls is not possible
5) Reading from the external databases is not possible with ide
6) Exceptional handling is not there
7) A neat formatted Reporting is not possible with ide
To eliminate the above issues we use Selenium RC


Designing Test Automation Framework with Selenium
by seetaram on June 19, 2011
Do we need to go for Test Automation? If yes, then which is the tool? If we straight away start automating test cases what are all the technical challenges we might face? Do we need a framework for Automation? How we go about designing a framework?
These are all the questions popup when we want to start Test Automation. Okay, let us start exploring answers for the above questions.
If there are hundreds of test scenarios which needs to be executed on each build then it will be a tedious task and error prone.  Because a Test Engineer might make mistakes while entering the test data and output might be wrong.  We can avoid such situations by automating the test cases.
Before selecting a tool for Test Automation, we need to analyze the technologies used for different UI components. For example, Java Swing components, Telerik controls, ExtJS tables, Ajax, Silverlight, Flex / Flash controls, etc. If we want to use Selenium as Test Automation tool then the first and foremost thing needs to be checked is whether the application is a Web Application. If so, then check whether most of the UI controls are identified by the Selenium. If more than 70% of the test cases can be automated then definitely we can go ahead and automate the test cases.
In order to handle large number of test cases we need to have a clear cut strategy for designing the framework. Some of the framework functionalities can be mentioned as follows:
1.    If there is any unhandled exception, then the execution should not stop.  Particular test scenario should be stopped and continue with the next scenario.
2.    Screen shots must be taken for each error so that analyzing the failures should be easy.
3.    Proper exception handling should be done in the framework.
4.    Proper naming convention should be used
5.    Avoid hard coding test data
6.    Test Data should be parameterized using external means such as XMLs, Database, Spreadsheet, etc.
7.    Logs should be created that makes life easier while analyzing the Test Execution
8.    Proper folder structure should be created.

If we need to create a Test Automation Framework with all the above mentioned features (or anything beyond this) for Selenium, then we need to use the programming language as JAVA and Eclipse as the IDE (Integrated Development Environment).
Test Automation Engineers should have knowledge of Java then it makes their life easier for automating the test cases.
We will discuss further about the framework in the next blog post.


Selenium Testing Framework Pt. 1: Testing Concepts
November 2nd, 2011 by Jason Smiley
This is part 1 of a 3-part guest blog series by Jason Smiley, QA Engineer at Gerson Lehrman Group.
When writing test scripts, you might find yourself trying to solve similar problems over and over again. So why not re-use the same solutions over and over again? The following framework will help you get the most out of your code without needing to do tons of maintenance every time something changes.
Before getting into specifics, lets first talk about what should be implemented when writing test scripts. At GLG, our tests typically go through a set of steps on the website. They also have to interact with elements on the site in order to accomplish these steps. Then there is the actual tests themselves, which review the displayed content on the site. Essentially, we have tests that assert the content on the site, a set of steps we need to take in order to perform these tests (which, for the sake of this blog post, I will describe as actions), and then the pages with elements that we are checking or interacting with.
When drawn as an ERD, we have something like this:

How can we best make use of this structure? We want tests to focus on use cases, actions that focus on what steps to take, and pages that allow us to interact with them. From a development standpoint, this means we have tests containing a list of actions that can be used to obtain the values required to check or change the state of the system under testing. Actions can interact with pages in order to complete these steps and make sure they accomplished their task. Pages can be used by actions or tests to add, edit, clear, or read data. Adding these relationships to the ERD, we get something like this:


What does this look like in code? How would we best accomplish this task? Well, that depends on what you are doing. For example, maybe you need to test 5 different types of projects, or maybe you need to test same page differently each time. Either way, as a coding standard, you should always design classes with a specific purpose. Anything that is shared should go into a base class for common functionality.
In the next blog post, I will describe how to set up different base classes for tests, pages, and actions. Then in part three of this blog post series, I will show you how to bring all of this together for testing your local projects.

Selenium Testing Framework Pt 2: Base Classes
November 17th, 2011 by Jason Smiley
This is part 2 in a 3-part guest blog post series by Jason Smiley, a QA Engineer at Gerson Lehrman Group.
In my last blog post, I showed what testing as a whole would look like, regardless of what we actually need to test. Just to recap, we have tests that check and validate results, actions that are a set of steps to take before having a value we can check, and pages that can be checked or interacted with.
For the sake of this article, let’s assume we will be testing several different websites with different code bases that are partially related. For example, we will have an admin site that can add, edit, and remove content from a different public content site. Assuming we have two different test projects, or one for each site, the first thing we need to do is create a base test, action, and page class that can be used by either test project to reduce the amount of code that needs to be written. These can also reduce any maintenance that needs to be done on updating common functionality.
Later, we can have another set of base classes that extend the shared base classes but are more specific to the project under test. Since there will be shared code, it is a good idea to create a separate project that can be referenced in your test projects. This allows you to change base code sets fairly easily, which can be useful if changing to a different testing framework.
Selenium Base Test Class
First, we’ll talk about a base test class. All tests need a browser, so first we must write a function that will create a browser. The tests will need to connect to the DB to allow for data checking, and it will also need utility functions so you can look at popups or switch between active frames. Let’s create SeleniumTestBase.cs class, which has these functions. In C#, it will look something like this:
public SeleniumTestBase
{
protected IWebDriver myDriver;
 
public SeleniumTestBase (IWebDriver webDriver)
{
myDriver = webDriver;
}
 
public DataTable GetData(string connString, string SQL)
{
//Some code which will query a DB for you
}
 
public IWebDriver StartBrowser(string browserType)
{
//Some code which will launch different types of browsers
}
 
public void SwitchToWindow(string handle)
{
//Some code which will switch windows for you
}
 
public void SwitchToFrame(string handle)
{
//Some code which will switch frames for you
}
 
public void LaunchUrl(string URL)
{
//Some code which will navigate directly to the specified URL.
}
 
public void Refresh()
{
//Some code to refresh the page you are currently on
}
}
Now, it’s important to note here that many of these functions don’t seem to be that hard to implement. In that case, why create a base class to encapsulate standard functionality already inherent to the Selenium Framework? There are two reasons for this.
One is that you will have less typing to do, which is always nice. The other is that, should you decide to change testing frameworks (from say Selenium 1 to Selenium 2), you will only need to update one class that handles all of the basic interactions. The ways of doing things may change from one framework release to the next. By encapsulating your code, you ensure that your code will always work the same as maintenance is performed since all tests will still call the same functions.
Selenium Action Base Class
Now we’ll move on to actions. Actions will execute the steps that will change the state of the website being tested (such as being signed in). Actions may also need to revert changes done by tests to a database for data cleanup, navigate to different pages, refresh the page, or interact with different frames and windows from the current active environment. Although the interactions between an action class and a page will be test specific, we can start writing the ways an action will interact with a browser or DB. A SeleniumActionBase.cs class will probably look something like this:
public SeleniumActionBase
{
protected IWebDriver myDriver;
 
public SeleniumActionBase(IWebDriver webDriver)
{
myDriver = webDriver;
}
 
public DataTable ExecuteSQL(string connString, string SQL = “”, string SPName = “”, string[] Parameters = new string[] {})
{
//Some code which will execute a query or stored proceedure for you
}
 
public void SwitchToWindow(string handle)
{
//Some code which will switch windows for you
}
 
public void SwitchToFrame(string handle)
{
//Some code which will switch frames for you
}
 
public void LaunchUrl(string URL)
{
//Some code which will navigate directly to the specified URL.
}
 
public void Refresh()
{
//Some code to refresh the page you are currently on
}
}
There are a couple of things I’d like to clarify about the above example when it comes to updating the database during test scripts:
•    If you are going to manually execute SQL to clean up your work after a test, you should be able to do so by using custom SQL or by calling stored procedures directly (hence the optional parameters). In my experience, it is always better to use a stored procedure rather than using your own SQL to update a DB to ensure that you aren’t creating a data issue.
•    You might not be able to actually update a DB directly using SQL due to internal security protocols. Or maybe you won’t even be comfortable doing this as your test code could break the DB. However, executing SQL to clean up your code is going to be much faster and more dependable than doing it through the UI. I’m not saying you should or should not clean up your tests this way, but if you are going to execute SQL to clean up your code, I’d advocate doing it this way.
Selenium Page Class
The last piece of the puzzle are the actual pages themselves. Pages are essentially just a grouping of page elements you wish to check and interact with. To code this the most efficient way, you should break the idea of a page into two separate classes.
One class, which I will refer to as a page class, is specific to the test project in the sense that it relates to the actual pages you want to test. From a coding perspective, these are the locator strings. Regardless of what framework you are using, you need to be able to find your elements. Typically, this is done by Id, XPath, or CSS, and generally won’t change unless the page you’re testing changes. Since some locator strings could be based on the browser start index, and browser start indexes can either be 1 or 0, the page class will need to know which browser is being used. Based on this, a SeleniumPageBase.cs class would look something like this:
public SeleniumPageBase
{
protected IWebDriver myWebDriver;
 
public SeleniumPageBase(IWebDriver webDriver)
{
myWebDriver = webDriver;
}
 
protected int browserIndex
{
get
{
return /*Code to get Browser index*/;
}
}
}
The second page class will handle the actual interactions between the test or action and the page. This is usually done by Selenium itself, however, a Selenium object isn’t always easy to use. A lot of times, you have to wait for the DOM to update the element you want to check, click, or interact with, especially if the page you are testing is using AJAX or Javascript. If an element fails, you might want to add additional error messaging to say what caused the interaction to fail. By using a level of encapsulation, you can better control the use of your Selenium or testing framework code.
Since this class is supposed to handle interactions of specific elements on a page, I will call this class a SeleniumPageElement. It is important to note that a page element class will need to mimic what a IWebElement –– or whatever framework you choose –– can do, as our actions and tests will be interacting with this class. By taking the testing framework’s place, we make it easier to swap out testing frameworks for new ones with little changes in test code.
Here is an example of what a SeleniumPageElement.cs class would look like:
public SeleneniumPageElement
{
public By myBy;
public IWebDriver myDriver;
public int? myIndex;
public SeleneniumPageElement myParent;
 
public SeleneniumPageElement(By locator, IWebDriver webDriver, SeleneniumPageElement parent = null, int? index = null)
{
myBy = locator;
myDriver = webDriver;
myIndex = index;
myParent = parent;
}
 
public IWebElement GetNow(string errorMessage = “”)
{
try
{
if(myParent != null)
{
if(myIndex != null)
{
return myParent.GetNow().FindElements(myBy)[MyIndex];
}
return myParent.GetNow().FindElement(myBy);
}
 
if(myIndex != null)
{
return myDriver.FindElements(myBy)[MyIndex];
}
return myDriver.FindElement(myBy);
}
catch(Exception e)
{
if(errorMessage.Equals(string.Empty) == false)
{
throw new Exception(errorMessage, e);
}
throw e;
}
}
public IWebElement WaitingGet(int seconds = 5, string errorMessage = “”)
{
//Waiting function using above method.
}
 
public void Click(int seconds = 5, string errorMessage = “”)
{
WaitingGet(seconds, errorMessage).Click();
}
In the last post of this series, I will go over how to connect what I covered in posts 1 and 2 and put it all together in your project.
Footnote: You will also need to write other waiting functions as well as interaction functions * to handle your framework calls. The above functions will handle the structure of the page element class to allow your other functions to handle specific interactions such as clicking or other types of waiting such as WaitUntilVisible(int seconds = 5, string errorMessage = “”) or WaitUntilNotVisible(int seconds = 5, string errorMessage = “”).
Selenium Testing Framework Part 3: Putting It All Together
December 6th, 2011 by Jason Smiley
This is the final post in a 3-part guest blog series by Jason Smiley, a QA Engineer at Gerson Lehrman Group. You can read his first post here and his second post here.
If you’ve been following along with my other posts on building a Selenium testing framework, you know we’ve covered some of the high-level testing concepts and base classes so far. Now that we have defined all our working parts, let’s see how we would pull this above code into our test projects. To summarize specficially what we talked about in the last blog, we have defined the following classes.
•    SeleniumTestBase.cs, which handles creating of the test browser, reading from the DB,  and handles changing of active windows or frames.
•    SeleniumActionBase.cs, which can update the DB and also can handle changing of the active windows or frames.
•    SeleniumPageBase.cs, which checks the starting number of the XPath browser index (IE uses 0 while all other browsers use 1).
•    SeleniumPageElement.cs, which handles waiting for and interacting with elements on the page.
Since I mentioned the above classes should be in an external project from your testing project, I will refer to these set of classes in compiled form as the OurSeleniumFramework.dll. This .dll file should be referenced in your test project so test, action, and page classes can extend the base classes we created.
When creating a test project to test a website, it is a good idea to create a project base test that will create all of our action and page classes, as well as having a project base action class that will create all our page classes. Page classes will create SeleniumPageElements, which will be used by action and test classes.
Example Test Project
To demonstrate this structure, I will show how base classes are created and how this can be used to test a login page which has a username field, password field, submit button, login confirmation message that appears after successful login, and error message that appears after unsuccessful attempts. I will now show what each class required to perform a basic login test will look like. I will also add notes in the tests to show why something is being done. See below for all the example test project files. The files will be:
1.    ProjectTestBase.cs: Handles NUnit setup, teardown, and page and action initialization functionality for tests.
2.    ProjectActionBase.cs: Handles page initialization functionality for actions.
3.    LoginTests.cs: Implements the tests for the login page.
4.    LoginActions.cs: Implements the steps required to do Login testing.
5.    LoginPage.cs: Handles the initialization for PageElement objects which will be used by actions and tests.
Example ProjectTestBase.cs
public ProjectTestBase : SeleniumTestBase
{
#region Action declarations
protected LoginActions _LoginActions;
#endregion
 
#region Page declarations
protected LoginPage _LoginPage;
#endregion
 
public ProjectTestBase (IWebDriver webDriver)
: base(webDriver) { }
 
public void CreateActions(IWebDriver webDriver)
{
_LoginActions = new LoginActions(webDriver);
}
 
public void CreatePages(IWebDriver webDriver)
{
_LoginPage= new LoginPage(webDriver);
}
 
[SetupTestFixture]
public virtual void setupTestFixture()
{
//Function is virtual so child test classes can have additional functionality.
 
//For this example project, nothing needs to be done on this level.
}
 
[Setup]
public virtual void setup()
{
//Function is virtual so child test classes can have additional functionality.
myDriver = StartBrowser(“firefox”);
CreateActions(myDriver);
CreatePages(myDriver);
LaunchUrl(“http://myhomepage.com”);
}
 
[Teardown]
public virtual void tearDown()
{
//Function is virtual so child test classes can have additional functionality.
myDriver.Quit();
}
 
[TeardownTestFixture]
public virtual void setupTestFixture()
{
//Function is virtual so child test classes can have additional functionality.
 
//For this example project, nothing needs to be done on this level.
}
}
Example ProjectActionBase.cs
public ProjectActionBase : SeleniumActionBase
{
 
#region Page declarations
protected LoginPage _LoginPage;
#endregion
 
public ProjectActionBase(IWebDriver webDriver)
: base(webDriver);
{
_LoginPage = new LoginPage(webDriver);
}
}
(I’d like to point out here that in this class, you can put common actions such as successful login so all action classes will be able to perform this step. This is just a nice-to-have, though, and not a must.)
Example LoginTests.cs
public LoginTests : ProjectTestBase
{
 
[Test]
public void successfulLoginTest()
{
_LoginActions.LoginAttempt(“Jason”, “Smiley”, true);
Assert.That(_LoginPage.ConfirmationMessage.Text, Is.EqualTo(“You are now logged in”).IgnoreCase, “You should have logged in successfuly but didn’t”);
}
 
[Test]
public void invalidLoginTest()
{
_LoginActions.LoginAttempt(“fake”, “fake”, false);
Assert.That(_LoginPage.ErrorMessage.Text, Is.EqualTo(“Invalid login”).IgnoreCase, “You should have gotten an error message but didn’t”)
}
}
Example LoginActions.cs
public LoginActions : ProjectActionBase
{
public void LoginAttempt(string username, string password, isValid = null)
{
LoginPage.UsernameTextField.Clear();
LoginPage.UsernameTextField.SendKeys(username);
LoginPage.PasswordTextField.Clear();
LoginPage.PasswordTextField.SendKeys(password);
LoginPage.SubmitBtn.Click();
 
if(isValid != null && isValid == true)
{
LoginPage.ConfirmationMessage.
WaitUntilVisibleAndPresent(“confirmation is not appearing after 5 seconds”);
}
 
if(isValid != null && isValid == false)
{
LoginPage.ErrorMessage.WaitUntilVisibleAndPresent(“error message is not appearing after 5 seconds”);
}
}
}
Example LoginPage.cs
public LoginPage : SeleniumPageBase
{
#region PageElement declarations
public PageElement UsernameTextField;
public PageElement PasswordTextField;
public PageElement ConfirmationMessage;
public PageElement ErrorMessage;
#endregion
 
public LoginPage(IWebDriver webDriver)
: base(webDriver)
{
UsernameTextField = new PageElement(By.Id(“username”), webDriver);
PasswordTextField= new PageElement(By.Id(“password”), webDriver);
ConfirmationMessage= new PageElement(By.Id(“success”), webDriver);
ErrorMessage= new PageElement(By.Id(“error”), webDriver);
}
}



Collection Interface

 List Interface


    The List interface extends Collection
   
    Declares the behavior of a collection that stores a sequence of elements. Elements can be inserted or             accessed by their position in the list, using a zero-based index. A list may contain duplicate             elements.

Set Interface

    The Set interface defines a set.
   
     It extends Collection

    Declares the behavior of a collection that does not allow duplicate elements.

    add( ) method returns false if an attempt is made to add duplicate elements to a set. It does not define any
    additional methods of its own.
SortedSet Interface

    SortedSet interface extends Set
   
    Declares the behavior of a set sorted in ascending order.

    SortedSet defines several methods that make set processing more convenient. To obtain the first object in             the set, call first( ). To get the last element, use last( ). You can obtain a subset of a sorted set by             calling subSet( ), specifying the first and last object in the set. If you need the subset that starts             with the first element in the set, use headSet( ). If you want the subset that ends the set, use             tailSet( ).


ArrayList Class

    Implements the List interface.

    ArrayList supports dynamic arrays that can grow as needed. That is, an ArrayList can dynamically
        increase or decrease in size.

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
}
}

The output from this program is shown here:
Initial size of al: 0
Size of al after additions: 7

Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]


LinkedList Class

    Implements the List interface.

    It provides a linked-list data structure.

    In addition to the methods that it inherits, the LinkedList class defines some useful methods of its own for             manipulating and accessing lists. To add elements to the start of the list, use addFirst( ); to add             elements to the end, use addLast( ). Their signatures are shown here:
            void addFirst(Object obj)
            void addLast(Object obj)
HashSet Class

    Implements the Set interface. 

    It creates a collection that uses a hash table for storage.

    Hash table stores information by using a mechanism called hashing. In hashing, the informational content
        of a key is used to determine a unique value, called its hash code. The hash code is then used as             the index at which the data associated with the key is stored. The transformation of the key into its             hash code is performed automatically—you never see the hash code itself. Also, your code can’t             directly index the hash table.

    The advantage of hashing is that it allows the execution time of basic operations, such as add( ),
        contains( ), remove( ), and size( ), to remain constant even for large sets.


// Demonstrate HashSet.
import java.util.*;
class HashSetDemo {
public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
System.out.println(hs);
}
}

The following is the output from this program:
[A, F, E, D, C, B]
As explained, the elements are not stored in sorted order, and the precise output may vary.
The elements are not stored in sorted order, and the precise output may vary.

LinkedHashSet Class


    Extends HashSet
   
    LinkedHashSet maintains a linked list of the entries in the set,in the order in which they were inserted.             when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order         in which they were inserted. Try substituting LinkedHashSet For HashSet in the preceding             program. The output will be
        [B, A, D, E, C, F]which is the order in which the elements were inserted.

TreeSet Class

    TreeSet provides an implementation of the Set interface

     Uses a tree for storage.

    Objects are stored in sorted, ascending order.

    Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large             amounts of sorted information that must be found quickly.


Few of the Exceptions thrown by methods of Collection classes:
    UnsupportedOperationException. As explained, this occurs if a collection cannot be modified. A    

    ClassCastException is generated when one object is incompatible with another, such as when an attempt     is made to add an incompatible object to a collection.

Method  to Add objects to collection :  Objects are added to a collection by calling add( ). Notice that add( ) takes     an argument of type Object. Because Object is a superclass of all classes, any type of object may be     stored in a collection. However, primitive types may not. For example, a collection cannot directly store     values of type int, char, double, and so forth.

Map Interface

    The Map interface maps unique keys to values.

     A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the         value in a Map object. After the value is stored, you can retrieve it by using its key.

    Maps revolve around two basic operations: get( ) and put( ).

    To put a value into a map, use put( ), specifying the key and the value. To obtain a value, call get( ),passing
        the key as an argument. The value is returned.
SortedMap Interface

    The SortedMap interface extends Map.

    It ensures that the entries are maintained in ascending key order.





HashMap Class

    HashMap class uses a hash table to implement the Map interface.

    This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for
        large sets.

import java.util.*;
class HashMapDemo {
public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));

// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}
Output from this program is shown here (the precise order may vary).
Todd Hall: 99.22
Ralph Smith: -19.08
John Doe: 3434.34
Jane Baker: 1378.0
Tom Smith: 123.22
John Doe’s current balance: 4434.34


LinkedHashMap Class

    Extends HashMap.
   
    LinkedHashMap maintains a linked list of the entries in the map, in the order in which they were inserted.             This allows insertion-order iteration over the map. That is, wheniterating a LinkedHashMap, the             elements will be returned in the order in which theywere inserted..

























Which are used widely ?

I think you're fine to use HashMap, HashSet, and ArrayList as your primary implementations. When you need a sorted set, it's good to know that TreeSet is available.



Summarizing All





Arraylist

public class Collections {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.quikr.com/");
        WebElement listelement = driver.findElement(By.name("categoryId"));
        //List<WebElement> listoptions = listelement.findElements(By.tagName("option"));
       
        ArrayList<WebElement> listoptions = (ArrayList<WebElement>) listelement.findElements(By.tagName("option"));
        for (int i = 1;i<listoptions.size();i++)
        {
            //System.out.println(listoptions.get(i).getText());
           
        }

       
        Iterator<WebElement> iterators1 = ((ArrayList<WebElement>) listoptions).iterator();
       
         while (iterators1.hasNext()){
             WebElement id1 = iterators1.next();
             System.out.println(id1.getText());
           
         }
       

    }

}

HashSet
import java.util.HashSet;


class HashSetDemo {
    public static void main(String args[]) {
// create a hash set
HashSet hs = new HashSet();
// add elements to the hash set
hs.add("B");
hs.add("A");
hs.add("D");
hs.add("E");
hs.add("C");
hs.add("F");
hs.add("A");    //This is duplicate so will not be added....

System.out.println(hs);
}
}

Output :

[D, E, F, A, B, C]      

The sequence of element is not stored as per element added.






TreeSet

// Demonstrate TreeSet.
import java.util.*;

class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set
TreeSet ts = new TreeSet();
// Add elements to the tree set
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("F");
ts.add("D");    // Duplicate is ignored
System.out.println(ts);
}
}


Output :

[A, B, C, D, E, F]

The sequence of element is stored in sorted order.



HashMap/HashTable

The following program illustrates HashMap. It maps names to account balances.
Notice how a set-view is obtained and used.


import java.util.*;

class HashMapDemo {

public static void main(String args[]) {
// Create a hash map
HashMap hm = new HashMap();
// Put elements to the map
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
hm.put("Ralph Smith", new Double(-19.08)); //Duplicate Entries will be ignored
// Get a set of the entries
Set set = hm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)hm.get("John Doe")).doubleValue();
hm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
hm.get("John Doe"));
}
}


Output from this program is shown here (the precise order may vary).
Todd Hall: 99.22
Ralph Smith: -19.08
John Doe: 3434.34
Jane Baker: 1378.0
Tom Smith: 123.22
John Doe’s current balance: 4434.34


TreeMap


The following program reworks the preceding example so that it uses TreeMap:

import java.util.*;

class TreeMapDemo {

public static void main(String args[]) {
// Create a tree map
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker", new Double(1378.00));
tm.put("Todd Hall", new Double(99.22));
tm.put("Ralph Smith", new Double(-19.08));
tm.put("Ralph Smith", new Double(-19.08));  //Duplicate entry is ignored
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe's account
double balance = ((Double)tm.get("John Doe")).doubleValue();
tm.put("John Doe", new Double(balance + 1000));
System.out.println("John Doe's new balance: " +
tm.get("John Doe"));
}
}

The following is the output from this program:
Jane Baker: 1378.0
John Doe: 3434.34
Ralph Smith: -19.08
Todd Hall: 99.22
Tom Smith: 123.22
John Doe’s current balance: 4434.34

2 comments:

  1. Do you need an urgent loan of any kind? Loans to liquidate debts or need to loan to improve your business have you been rejected by any other banks and financial institutions? Do you need a loan or a mortgage? This is the place to look, we are here to solve all your financial problems. We borrow money for the public. Need financial help with a bad credit in need of money. To pay for a commercial investment at a reasonable rate of 3%, let me use this method to inform you that we are providing reliable and helpful assistance and we will be ready to lend you. Contact us today by email: daveloganloanfirm@gmail.com Call/Text: +1(501)800-0690 And whatsapp: +1 (501) 214‑1395

    NEED A LOAN?
    Ask Me.

    ReplyDelete

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...