Wednesday, 16 April 2014

How to execute selenium webdriver tes script parallel in multiple browser using testng parameter annotation.


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class MultiBrowser {
 private WebDriver driver;

 @Parameters("browser")
 @BeforeMethod
 public void setup(String browser)
 {
  if(browser.equalsIgnoreCase("firefox"))
  {
   driver = new FirefoxDriver();
  }
  else if(browser.equalsIgnoreCase("iexplorer"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.ie.driver", "Drivers\\IEDriverServer.exe");
   driver = new InternetExplorerDriver();
  }
  else if(browser.equalsIgnoreCase("chrome"))
  {
// Update the driver path with your location
   System.setProperty("webdriver.chrome.driver", "Drivers\\chromedriver.exe");
   driver = new ChromeDriver();
  }
  driver.manage().window().maximize();
 }

 @AfterMethod
 public void tearDown()
 {
 driver.quit();
 }

 @Test
 public void testMultiBrowser() throws InterruptedException
 {
  driver.get("http://www.google.com");
  Thread.sleep(3000);
 }
}

2. Now we need to create TestNG.xml and write the following code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="MultiBrowser">
       <test name="TestFirefox" verbose="10">
              <parameter name="browser" value="firefox" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="ChromeTest">
              <parameter name="browser" value="chrome" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
       <test name="IETest">
              <parameter name="browser" value="iexplorer" />
              <classes>
                     <class name="MultiBrowser" />
              </classes>
       </test>
</suite>

3. Now run the code from TestNG.xml

You can observer all the three browsers will open and perform the task at a time.

Monday, 14 April 2014

Top 20 Useful Commands in Selenium Webdriver.


1. Creating New Instance Of Firefox Driver

WebDriver driver = new FirefoxDriver();
Above given syntax will create new instance of Firefox driver.

 2. Command To Open URL In Browser

driver.get("http://only-testing-blog.blogspot.in/2013/11/new-test.html");
This syntax will open specified URL in web browser.

3. Clicking on any element or button of webpage

driver.findElement(By.id("submitButton")).click();
Above given syntax will click on targeted element in webdriver.

4. Store text of targeted element in variable

String dropdown = driver.findElement(By.tagName("select")).getText();
This syntax will retrieve text from targeted element and will store it in variable = dropdown.

5. Typing text in text box or text area.
driver.findElement(By.name("fname")).sendKeys("My First Name");
Above syntax will type specified text in targeted element.

6. Applying Implicit wait in webdriver

driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
This syntax will force webdriver to wait for 15 second if element not found on page.

7. Applying Explicit wait in webdriver with WebDriver canned conditions.

WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//div[@id='timeLeft']"), "Time left: 7 seconds"));
Above 2 syntax will wait for till 15 seconds for expected text "Time left: 7 seconds" to be appear on targeted element.

8. Get page title in selenium webdriver

driver.getTitle();
It will retrieve page title and you can store it in variable to use in next steps.

9. Get Current Page URL In Selenium WebDriver

driver.getCurrentUrl();
It will retrieve current page URL and you can use it to compare with your expected URL.

10. Get domain name using java script executor

JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return document.domain");
Above syntax will retrieve your software application's domain name using webdriver's java script executor interface and store it in to variable.

11. Generate alert using webdriver's java script executor interface

JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
It will generate alert during your selenium webdriver test case execution.


12. Selecting or Deselecting value from drop down in selenium webdriver.
Select By Visible Text
Select mydrpdwn = new Select(driver.findElement(By.id("Carlist")));
mydrpdwn.selectByVisibleText("Audi");
It will select value from drop down list using visible text value = "Audi".
Select By Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByValue("Italy");
It will select value by value = "Italy".
Select By Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.selectByIndex(0);
It will select value by index= 0(First option).

Deselect by Visible Text
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByVisibleText("Russia");
It will deselect option by visible text = Russia from list box.
Deselect by Value
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByValue("Mexico");
It will deselect option by value = Mexico from list box.
Deselect by Index
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectByIndex(5);
It will deselect option by Index = 5 from list box.
Deselect All
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
It will remove all selections from list box.


isMultiple()
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
It will return true if select box is multiselect else it will return false.

13. Navigate to URL or Back or Forward in Selenium Webdriver

driver.navigate().to("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
1st command will navigate to specific URL, 2nd will navigate one step back and 3rd command will

14. Verify Element Present in Selenium WebDriver

Boolean iselementpresent = driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
It will return true if element is present on page, else it will return false in variable iselementpresent.

15. Capturing entire page screenshot in Selenium WebDriver

File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
It will capture page screenshot and store it in your D: drive.

16. Generating Mouse Hover Event In WebDriver

Actions actions = new Actions(driver);
WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform();
Above example will move mouse on targeted element.

 17. Handling Multiple Windows In Selenium WebDriver.
1. Get All Window Handles.
Set<String> AllWindowHandles = driver.getWindowHandles();
2. Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];
3. Use window handle to switch from one window to other window.
driver.switchTo().window(window2);
Above given steps with helps you to get window handle and then how to switch from one window to another window

18. Check Whether Element is Enabled Or Disabled In Selenium Web driver.

boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
Above syntax will verify that element (text box) fname is enabled or not. You can use it for any input element.

 19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
It will disable fname element using setAttribute() method and enable lname element using removeAttribute() method.

 20. Selenium WebDriver Assertions With TestNG Framework

assertEquals
Assert.assertEquals(actual, expected);
assertEquals assertion helps you to assert actual and expected equal values.

 assertNotEquals
Assert.assertNotEquals(actual, expected);
assertNotEquals assertion is useful to assert not equal values.

assertTrue
Assert.assertTrue(condition);
assertTrue assertion works for boolean value true assertion.

assertFalse
Assert.assertFalse(condition);

Thursday, 10 April 2014

Database Connectivity with Selenium in Java


import java.sql.*;
import javax.sql.*;

public class dbconnection
{
public static void main(String args[])
{
String email;
String dbUrl = "jdbc:mysql://localhost:3306/test";  //This URL is based on your IP address
String username="username"; //Default username is root
String password="password"; //Default password is root
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select email from users where user_id = 1;";

try 
{

Class.forName(dbClass);
Connection con = DriverManager.getConnection (dbUrl,username,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) 
{
dbtime = rs.getString(1);
System.out.println(email);
} //end while

con.close();
} //end try

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

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

}  //end main

}  //end class

Tuesday, 25 March 2014

TestNG Annotations

What’s the hierarchy of TestNG annotations? 


Ans:
  1. org.testng.annotations.Parameters (implements java.lang.annotation.Annotation)
  2. org.testng.annotations.Listeners (implements java.lang.annotation.Annotation)
  3. org.testng.annotations.Test (implements java.lang.annotation.Annotation)
  4. org.testng.annotations.AfterMethod (implements java.lang.annotation.Annotation)
  5. org.testng.annotations.BeforeTest (implements java.lang.annotation.Annotation)
  6. org.testng.annotations.BeforeMethod (implements java.lang.annotation.Annotation)
  7. org.testng.annotations.Optional (implements java.lang.annotation.Annotation)
  8. org.testng.annotations.AfterTest (implements java.lang.annotation.Annotation)
  9. org.testng.annotations.Guice (implements java.lang.annotation.Annotation)
  10. org.testng.annotations.BeforeGroups (implements java.lang.annotation.Annotation)
  11. org.testng.annotations.ExpectedExceptions (implements java.lang.annotation.Annotation)
  12. org.testng.annotations.TestInstance (implements java.lang.annotation.Annotation)
  13. org.testng.annotations.NoInjection (implements java.lang.annotation.Annotation)
  14. org.testng.annotations.AfterSuite (implements java.lang.annotation.Annotation)
  15. org.testng.annotations.AfterClass (implements java.lang.annotation.Annotation)
  16. org.testng.annotations.AfterGroups (implements java.lang.annotation.Annotation)
  17. org.testng.annotations.DataProvider (implements java.lang.annotation.Annotation)
  18. org.testng.annotations.BeforeSuite (implements java.lang.annotation.Annotation)
  19. org.testng.annotations.BeforeClass (implements java.lang.annotation.Annotation)
  20. org.testng.annotations.Factory (implements java.lang.annotation.Annotation)
  21. org.testng.annotations.Configuration (implements java.lang.annotation.Annotation)
  22. org.testng.annotations.ObjectFactory (implements java.lang.annotation.Annotation)

Friday, 21 March 2014

Sample Keyword Driven framework in Selenium Webdriver.


Framework: It is a set of Guidelines designed by an Expert in a generic way to accomplish a task in an effective and efficient manner.

Please find the below sample code for Keyword driven framework in Selenium Web driver.

package com.project1;

import java.io.File;
import java.io.IOException;
import java.util.List;

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

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;

public class Keyword_Driven {
   
       //Initiate Driver
       webdriver driver=new firefoxdriver();
public static void main(String[] args)
{
   
        //Login
        driver.get("http://newtours.demoaut.com/");
     
   
              Workbook workbook;
              try {

                     File f=new File("C:\\Users\\Public\\Documents\\Test Excel\\Keyword_driven.xls");
                  Fileinputstream fis=new Fileinputstream(f);
                     workbook = Workbook.getWorkbook(fis);
                     Sheet sheet = workbook.getSheet(0);
                 
              //code to read Test Case
                     int row=sheet.getRows();
                     for(int i=1;i<row;i++)
                     {
                           String Testcasename=sheet.getCell(0,i).getContents().toString();
                           //Call function ExecuteFunction to Read Mapped Function
                           ExecuteFunction(Testcasename);
                       
                 
                     }
                     //Close Browser
                     quitdriver();
                 
              } catch (BiffException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              } catch (IOException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
           
}
public static void ExecuteFunction(String Casename)
{
       String Option=Casename.trim();
   
 if(Option.equalsIgnoreCase("TC_Login") )
 {
   
        //Execute Login Function
        Login("Mercury", "mercury");
 }
 else if(Option.equalsIgnoreCase("TC_Book Flight"))
 {
        //Execute FlighBook Function
        FlightBook();
 }
 else if(Option.equalsIgnoreCase("TC_Logout"))
 {
       //Execute Logout
        Logout();
 }
 }
public static void Login(String Username,String Password)
{
        driver.findElement(By.name("userName")).sendKeys(Username);
        driver.findElement(By.name("password")).sendKeys(Password);
        driver.findElement(By.name("login")).click();
}
public static void FlightBook()
{
        Select Passangers= new Select(driver.findElement(By.cssSelector("select[name='passCount']")));
        Passangers.selectByVisibleText("2");
        Select Departingfrom = new Select(driver.findElement(By.cssSelector("select[name='fromPort']")));
        Departingfrom.selectByVisibleText("Frankfurt");
        Select FromMonth = new Select(driver.findElement(By.cssSelector("select[name='fromMonth']")));
        FromMonth.selectByVisibleText("September");
        Select ArrivingIn = new Select(driver.findElement(By.cssSelector("select[name='toPort']")));
        ArrivingIn.selectByVisibleText("New York");
        Select ToMonth = new Select(driver.findElement(By.cssSelector("select[name='toMonth']")));
        ToMonth.selectByIndex(10);
        driver.findElement(By.xpath("/html/body/div/table/tbody/tr/td[2]/table/tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[5]/td/form/table/tbody/tr[9]/td[2]/font/font/input")).click();
        driver.findElement(By.name("findFlights")).click();
        driver.findElement(By.name("reserveFlights")).click();
        driver.findElement(By.name("passFirst0")).sendKeys("Name1");
        driver.findElement(By.name("passLast0")).sendKeys("LastName");
        driver.findElement(By.name("creditnumber")).sendKeys("1234566");
        driver.findElement(By.name("buyFlights")).click();
     
}
public static void Logout()
{
 driver.findElement(By.linkText("SIGN-OFF")).click();
}

public static void quitdriver()
{
 driver.quit();
}

}

Friday, 31 January 2014

Putting Assertion to a Web element in Webdriver.


WebDriver driver= new FirefoxDriver(); driver.get("http://google.com");  
    WebElement element = driver.findElement(By.className("gbqfba")); String strng = element.getText(); System.out.println(strng);  Assert.assertTrue("Google Search", strng);

Wednesday, 22 January 2014

Regular Expressions in QTP


Regular Expressions in QTP
Sometimes there might be situations where values of objects keep on varying and QTP may fail to recognize them or checkpoints might get failed as the expected and actual data are not matching. In such cases Regular expressions come into picture. It enables QTP to identify objects and text strings with varying values.Regular expressions can be used:

1. In identifying the property values of an object

2. In parametrization

3. For creation of checkpoints on objects with varying values

1. In identifying property values of an object:

In this concept, let’s see how to handle QTP when a value of an object is varied. Let’s walk through this section with a small example:

Assume that you have to record a scenario of verifying the mails in a mail account. Open the mail with valid username and password. Now click on Inbox. When you have opened your mail account assume that there are 5 mails. So the inbox would be showing Inbox (5). When you click on that, the mails get displayed. Following would be the statement that gets generated when clicked on Inbox:

Browser(“Gmail”).Page(“Gmail”).Link(“Inbox(5)”).click

Now when the same script is run again, QTP fails at the same step as the number of mails in the inbox is 4. Or even more if some new mails have come. The script execution doesn’t get passed unless the total number of new mails is again 5. We make use of regular expression here as the value for the number of mails keeps varying.

For creating a regular expression, go to object repository from ResourcesàObject repository. Select the link object Inbox (5) from object list displayed in the left side.

Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUyR4S8fIebPZVlPPkyNDoCLYTvIB_UzJvdZeaWiPyuIWGAtL8eI3OHLN0g-kljkbSgOW3zr0AnqORV6PP-s5o-JBz_38dE7grmbq-2S19pEr1ULnWZ-jTFly3YuXH9-tKTXNT8IhJLiF5/s400/RE_1.JPG

Go to the object properties screen displayed in the right side of the screen. Select the property that has the value Inbox (5). Click on the configure icon that gets displayed there.

Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdmJhB3V755FiU6mPaNYiTNlPDquuhyphenhyphenzu7sK3izIiGqzQj9MSAYyMY3CWUK76YsHNp7WpSSRqFODnkIbWhNU68-sAFAzb8b3OY4NUBF7Nes-zXgHrPfT3lfLMRBYjWpbLh2kOnM-QCXD9v/s400/RE_2.JPG


‘Value configuration Options’ dialog box gets displayed.


Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEihThyphenhyphenGsyBELN2A9W3hcZxzF_bIyf95QbD9cc8-IVSuevG8QxyJvYZBTrY-MnqkBt9_zifPOLP7wq0Z-Qewujsy4n3LDyeBbyR_Q3OTwDhXuskLF5kdelFGtqGmo8eImxTZogvwVNpIg5MM/s400/RE_3.JPG

Check the Regular expressions check box. A dialog box gets raised asking the user whether to add a back slash before each special character in order to treat it literally. As we have special characters ‘(‘ and ‘)’ we need to click on Yes and QTP adds a slash character before both the Parenthesis characters.

If you want qtp script to be successful for 0-9 mails then give the following value in Constant edit box:

Inbox\([0-9]\)

For 0-99 mails

Inbox\([0-9][0-9]\)

For 0-999 mails

Inbox\([0-9][0-9][0-9]\)

Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiL9LOQLThdWpbctbn3p0mz_8WBZg2d0CitGrm_Xv1AfyW6O4oAaKtOhmtIY5ZmJT1pkCI1DJLLqbgUaZiAgObi45D2T91xH2pgEYtce35tX8uTx4W_TER9i5LlozFdA-RTP8iDGU2A5rP7/s400/RE_4.JPG

Click on OK and close the object repository window. For first option QTP executes the scripts successfully if the Inbox has 0-9 mails. Second option executes successfully for 0-99 mails and third option for 0-999 mails.

2. In Parameterization:
In some cases, we need to parameterize the varying values in the script. In such cases we parameterize the values and use the regular expression in parameterized value i.e., in data table sheet where the value is present. Using the same example mentioned above lets discuss how can be regular expressions in parameterization process.

Select the link object Inbox (5) from object list displayed in the left side of Object repository.

Go to the object properties screen displayed in the right side of the screen. Select the property that has the value Inbox (5). Click on the configure icon that gets displayed there.

‘Value configuration Options’ dialog box gets displayed. Set the Parameter Radio button and select the location of data table (global/local). Enter a title for the column.Now check the Regular expressions checkbox in advanced configurations option. Click on Yes in the dialog box that gets displayed.


Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgrFxLz6SeNwTaAo79VdYw1ZQW09k2P0snnrVdw9-xPonWDA2RoGSi_EEk_j003Y9kD1OKIA0k72v3mcpjEWeKroh1YicebkanEm92lxPDodrlbbbs-Z0rwUTCi1IY2yrG-8lg50DTj8vmo/s400/RE_5.JPG

Click on OK and close the object repository window. If you want QTP script to be successful for 0-9 mails then give the following value in Data table sheet of QTP:

Inbox\([0-9]\)

For 0-99 mails

Inbox\([0-9][0-9]\)

For 0-999 mails

Inbox\([0-9][0-9][0-9]\)

Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh_5uEoesAKgWAF2A9ZN3wzzzfc51Rbjyr436yYT2QGMwChQfbpgrpKQ-doyH2xus8B-qMM5eh8MBRiGFZBX41dldN8D_T1rlX7VBpKG-4QBGdh0rgJ6o2pbIa1_NeeWY3MU4VJn9M31jDO/s400/RE_6.JPG
For first option QTP executes the scripts successfully if the Inbox has 0-9 mails. Second option executes successfully for 0-99 mails and third option for 0-999 mails. Using this example, the values can be changed directly in the data table sheet.

3. For creation of checkpoints on objects with varying values

Assume that you have to create a text check point on some text which gets varied continuously. In the same example mentioned above, you need to insert a text checkpoint on Inbox (5) which gets varied basing on the number of mails available in the inbox. When the checkpoint is created, it takes Inbox (5) as the expected value and when the same script is run again when there are 4 mails in the inbox, and then the checkpoint fails. To overcome such situations, regular expressions is used again.

Insert a checkpoint by selecting Insert--&gt;Checkpoint--&gt;Text Checkpoint. (Make sure that QTP is in recording mode)

Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgXXCiXdIC3CtOKR2_NBfH_h_mnU_ixJk4xmz5N1ZKj0L2o79rYyABYUF30BiZ2tciFA5R55cXJgZsoKpgeT3FNg7-ZZ58BFXLIrRK9MAE96vBn3zeji_TTLoMrzZnVCmHb4fpg-mmPskMM/s400/RE_7.JPG

Select the text on which you want to insert text checkpoint (i.e., Inbox (5)). Text checkpoint properties window gets opened.Make sure that the radio button is set to constant dialog box. Click on Constant Value options icon that gets displayed there.

Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1YdWoAMltTr9TUD46WV6BWv7GAGkcakO1urov5v5v_VIxKbLr0PsWVfN8gI19Ht14jqfVCDgFpvd8z9FIO6XO_tpBD6IBhutVXvVVXpHO_MvAP9ivBlvUjs7XWxsmXCPKcc90uFXCzh00/s400/RE_8.JPG
‘Constant Value options’ dialog box gets displayed. Now check the regular expressions check box and Click on yes in the dialog box that gets displayed to treat ‘(‘ and ‘)’ as literal characters. Now in the same way as mentioned in the above two examples enter the data as per your requirement.


Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgmnlVvIpXQ-23uWlfmLJ_Rblc4fXreEfZMdc0AlMyBL1I_QMto6oJezJbCpqL1F6bvq4D1Z-Y9JmJGO_ng_IIGLGn8O_3XHWD4PUuoXlyQOlKukZacnGEfmBqW3DLqe1MACluUgDvkviR7/s400/RE_9.JPGFor 0-9 mails

Inbox\([0-9]\)

For 0-99 mails

Inbox\([0-9][0-9]\)

For 0-999 mails

Inbox\([0-9][0-9][0-9]\)

Click on OK and close the Text checkpoint properties window. For first option QTP checkpoint gets passed if the Inbox has 0-9 mails. Second option gets passed for 0-99 mails and third option for 0-999 mails.