23 December, 2014

How to know if web-page is open or closed?

After calling driver.close() the value of driver is set to
FirefoxDriver: firefox on WINDOWS(4b4ffb1e-7c02-4d9c-b37b-310c771492ac)
But if you call driver.quit() then it sets the value of driver to
FirefoxDriver: firefox on WINDOWS (null)
So if you're checking the browser window after calling driver.quit() then you will be able to know by below implementation.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
driver.quit();              
if(driver.toString().contains("null"))
{

System.out.print("All Browser windows are closed ");
}
else
{
//open a new Browser
}

How to switch the Browser windows using different driver instances.

In the below program we have created two browser instances i.e driver and driver1.
with one driver instance we are opening one URL and with second driver instance other URL.
Below code shows how we can switch the browser windows using different driver instances.

 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import org.openqa.selenium.support.ui.WebDriverWait;  
 public class FrameWorkBase {  
      // 'driver' and 'driver1' are two instances created.  
   public static WebDriver driver,driver1;  
   public static WebDriverWait wait;  
   public static String Parentwindow;  
   public static void main (String []args) throws Exception  
     {  
     driver= new FirefoxDriver();
     driver.manage().window().maximize();  
     wait=new WebDriverWait(driver, 10);  
     driver.get("http://www.yahoo.com");  
     System.out.println(driver.getTitle());  
     Parentwindow = driver.getWindowHandle();  
     for ( String currentwindow : driver.getWindowHandles())   
           driver.switchTo( ).window(currentwindow);   
              {   
                   driver1=new FirefoxDriver();  
                driver1.manage().window().maximize();  
                driver1.get("https://translate.google.co.in/");  
                System.out.println(driver1.getTitle());               
                driver.switchTo().window(Parentwindow);  
              }   
              System.out.println(driver.getTitle());  
 }  
 }  

18 December, 2014

How to open a Link in new tab using Selenium Web-driver.

  • If you want to manually open the Link in New Tab you can achieve this by performing Context Click on the Link and selecting 'Open in new Tab' option. Below is the implementation in Selenium web-driver with Java binding.
Actions newTab= new Actions(driver);
WebElement link = driver.findElement(By.xpath("//xpath of the element"));

//Open the link in new window
newTab.contextClick(link).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
  • Web-driver handles new tab in the same way to that of new window. You will have to switch to new open tab by its window name.
driver.switchTo().window(windowName);
You can keep track of window-names which will help you to easily navigate between tabs.

10 December, 2014

How to Close three different Browser Instances using 'driver.quit()' ?

 Below code will open three browsers (IE,Firefox and Chrome) and will open URL and finally it closes all the three opened browsers by 'driver.quit()' function.

 import java.util.ArrayList;  
 import java.util.List;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 public class Test   
 {  
   private List<WebDriver> drivers;  
     public Test( )  
      {  
          this.drivers = new ArrayList<WebDriver>();  
      }  
 public void CloseAll()  
      {  
     for(WebDriver d : drivers)  
       {  
       d.quit();  
       }  
      }  
 public static void main(String[] args)  
      {  
   Test1 sc = new Test1();  
   sc.IE("http://google.com");  
   sc.Firefox("http://google.com");  
   sc.Chrome("http://google.com");  
   sc.CloseAll();  
      }  
 //Internet Explorer driver  
 public void IE(String URL)  
     {  
   //Set you IEDriver path as per your System Path  
   System.setProperty("webdriver.ie.driver","S:\\IE Driver\\IEDriverServer.exe");  
   WebDriver driver = new InternetExplorerDriver();  
   driver.get(URL);  
   this.drivers.add(driver);  
      }  
 //Firefox driver  
 public void Firefox(String URL)  
     {  
   WebDriver driver = new FirefoxDriver();  
   driver.get(URL);  
   this.drivers.add(driver);  
     }  
 //Chrome driver  
 public void Chrome(String URL)  
     {  
   //Set you ChromeDriver path as per your System Path  
   System.setProperty("webdriver.chrome.driver","S://Chrome Driver//chromedriver.exe");  
   WebDriver driver = new ChromeDriver();  
   driver.get(URL);  
   this.drivers.add(driver);  
    }  
 }  

}

28 November, 2014

How to perform Scroll operation in Selenium-Webdriver

Scroll Down:

 import org.openqa.selenium.JavascriptExecutor;   
 WebDriver driver = new FirefoxDriver();  
 JavascriptExecutor jse = (JavascriptExecutor)driver;  
 jse.executeScript("scroll(0, 250)"); //y value '250' can be altered  

-------------------------------------------------------------------------------------------------
Scroll up:


 JavascriptExecutor jse = (JavascriptExecutor)driver;  
 jse.executeScript("scroll(250, 0)"); //x value '250' can be altered  

----------------------------------------------------------------------------------------------------
Scroll bottom of the Page:


 JavascriptExecutor jse = (JavascriptExecutor)driver;  
 jse.executeScript("window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));");  
 (or)  
 Actions actions = new Actions(driver);  
 actions.keyDown(Keys.CONTROL).sendKeys(Keys.END).perform();  

-----------------------------------------------------------------------------------------------------
Full scroll to bottom in slow motion:

 for (int second = 0;; second++)   
  {  
     if(second >=60)  
     {  
       break;  
     }  
  ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,400)", ""); //y value '400' can be altered  
  Thread.sleep(3000);  
  }  
 (or)  
  JavascriptExecutor jse = (JavascriptExecutor)driver;  
  for (int second = 0;; second++)  
     {  
        if(second >=60)  
         {  
       break;  
         }  
       jse.executeScript("window.scrollBy(0,800)", ""); //y value '800' can be altered  
       Thread.sleep(3000);  
     }  

----------------------------------------------------------------------------------------------------------------------
Scroll automatically to your WebElement:

 

 Point hoverItem =driver.findElement(By.xpath("Value")).getLocation();  
 ((JavascriptExecutor)driver).executeScript("return window.title;");    
 Thread.sleep(6000);  
 ((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+(hoverItem.getY())+");");  
 // Adjust your page view by making changes right over here (hoverItem.getY()-400)  
 (or)  
 ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", driver.findElement(By.xpath("Value')]")));  
 (or)  
 WebElement element = driver.findElement(By.xpath("Value"));  
 Coordinates coordinate = ((Locatable)element).getCoordinates();  
 coordinate.onPage();  
 coordinate.inViewPort();  

How to perform Right-click/Context-click in Selenium Webdriver.

Using 'Action class' we can easily perform Right-click/Context-click on any Web-element.

Step 1: Store the Path of Web-element to be Right-clicked  in to the Web-element.
             Lets say  We have a Web-element name Test_element which we are right-clicking.
Step2:  We will use Action class to perform the Right-click/Context-click on our Web-element.
                              
 Actions actions = new Actions(driver);    
                 Action action=actions.contextClick(Test_element).build();     
                 action.perform();   

27 November, 2014

How to detect an element from the Drop down menu using Variable name.

We all know that we can select the elements from the Drop-down menu using three common methods. i.e. selectByIndex, selectByValue and selectByVisibleText.
But the problem arises when we have to detect the web-element by Variable name.
Here might be the situation,  When we are passing the Variable value by the Variable name  and want to select the option from the Drop-down menu using Variable name then we cannot use any of the available methods to select the Drop-down option.

So in this situation we can try in below manner to get the required Drop-down option from the Drop-down menu.


 WebElement Drop_down_menu = driver.findElement(By.xpath("//select[@name='RubricID']"));  
  List<WebElement> Drop_down_option = Drop_down_menu.findElements(By.xpath(".//option[contains(text(),'" + Variable_name_ + "')]"));  
  for (WebElement option : Drop_down_option)   
        {  
            if (!option.isSelected())   
             {  
              option.click();  
             }  
          }  


where   'Drop_down_menu' will save the path of Drop down box on your web page.
             'Drop_down_option' will  be the xpath of the required element from the Drop down box in                  which we will use Variable name.
             'Variable_name'  will be the variable name used in your code.


26 November, 2014

How to handle Modal Dialog Box in Selenium Webdriver.

What is Modal Dialog Box?
Function Modal Dialog Box is used to deal with Modal Type Windows.
When we open a window using this function Java-script execution gets suspended till the window gets closed.
Here parent window is expecting some return value from the pop-up window.
So the problem in Selenium Web-driver is that when we open a Modal window then accessibility to the parent window is Blocked.

Problem in Selenium with Modal Dialog Box.
Selenium works with Java-script. When show Modal dialog is called Javascript gets suspended from the parent.
Selenium whose handle still pointing to the Main window gets suspended.
As a result all the successive commands after that gets suspended.

How to handle Modal Dialog Box in Selenium Web-driver.
Pre-requisite: I believe when a Modal Dialog Box is opened then the cursor is on the Modal Dialog Box.
In that case we can handle the operation on the Modal Dialog Box using Robot class.

Lets say Below is a screen-shoot of one the Modal Dialog Box where it accepts a String and after pressing an Enter key its gets close.

 After we perform the action which opens Modal Dialog box, Try below Method
       
 Robot robot = new Robot();  
     robot.keyPress(KeyEvent.VK_TAB);  
     robot.keyRelease(KeyEvent.VK_TAB);  
     StringSelection data_to_enter= new StringSelection("Data to Enter");  
     Toolkit.getDefaultToolkit().getSystemClipboard().setContents(data_to_enter, null);  
     Thread.sleep(7000);   
     robot.keyPress(KeyEvent.VK_CONTROL);  
     robot.keyPress(KeyEvent.VK_V);  
     robot.keyRelease(KeyEvent.VK_V);  
     robot.keyRelease(KeyEvent.VK_CONTROL);  
     robot.keyPress(KeyEvent.VK_ENTER);  
     robot.keyRelease(KeyEvent.VK_ENTER);  


In StringSelection enter the Data which is required to be sent in the text-field on Modal Dialog Box and it will save that string into system's clip board and next action will paste that string at the cursor position.
The Rest actions are handled by Robot class which will pass the key events in the manner .(cntrl + V, Enter).

Let me know if you find the above implementation useful in your code.

19 November, 2014

How to perform Right click on the Web element and select an option from context menu in Selenium Webdriver?

Step1: Store the path of web-element to be right clicked and web-element to be selected from context menu.
        
      WebElement rightClickelement = driver.findElement(by.---( ));  
      WebElement contextMenuelement = driver.findElement(by.---( ));  


Step2: Use Action class
          
       Actions actions = new Actions(driver);  
       Action action = actions.contextclick(rightClickelement).build( );  
       action.perform( );  


Step3: Click on the element  from the Context menu of the web element.
          
    contextMenuelement.click( );   

How to perform Drag and Drop operation in Selenium Webdriver?

Step1: Store the path of Source and Target in the  Web-Elements.
          
       WebElement Source = driver.findElement(by.---( ));  
       WebElement Target = driver.findElement(by.---( ));  


Step2: Using the Action class  create an object of it.
          
  Actions builder = new Actions(driver);  


Step3: Perform Drag and Drop operation
         
      Action drag = builder.clickAndHold(Source).moveToElement(Target).release(Target).build( );  
      drag.perform( );  

How to click on the Mouse-Hover Text element in Selenium Webdriver?

Step1: Locate the path of Mouse-Hover element and store them in the web element.
          
 WebElement Mhovertestelement = driver.findElement(By.----( ));  


Step2: User Action class
          
 Actions builder = new Actions(driver)  

         
Step3: Go to the Web element and perform
         
 builder.moveToElement(Mhovertestelement).perform( );   


Step4: After Mouse-Hover you can easily click on the web element to be selected. 

How to select an option from the Dropdown element in Selenium Webdriver?

Step1: Create a Web-element and assign the path of Drop-down element to the Web-element.          
 WebElement Dropdownelementtest = driver.findelement(by.-----());  

Step2: Create a Select object and assign a Web-element object to the Select object created.          
  Select Dropdownoptiontest = new Select(Dropdownelementtest);  

Step3: Select the value from the Dropdown element.
           We have three types of method available to select option from Dropdown list
            Select by Index          
 Dropdownoptiontest.selectByIndex(" ");  

           Select by value          
 Dropdownoptiontest.selectByValue(" ");  

           Select by Visible Text          
 Dropdownoptiontest.selectByVisibleText(" ");  

How to switch to different browser window from current window in Selenium webdriver?

Step1: Store the Main window handle
          
 String Parentwindow = driver.getWindowHandle( );  


Step2: Click on the Link which will open the new Browser window

Step3: Switch to the new open browser window.
          
  for ( String currentwindow : driver.getWindowHandles())  
  driver.switchTo( ).window(currentwindow);  
       {  
       // Perform your operations on the current window    
         driver.close( )  
       }  


Step4: Return to the Main window
          
  driver.switchTo().window(Parentwindow);  


What is System.exit(0),System.exit(1) and System.exit(-1)?

  • System.exit(0) - It indicates that execution runs successfully.

  • System.exit(1)- It indicates something which is expected went wrong.
                                   Example : Bad command Line, File not found, could not connect to server.
  • System.exit(-1)- It indicates something which is Un-expected went wrong.
                                   Example : System error, Unanticipated exception, Externally forced termination.

 

What is the difference between 'findElement' and 'findElements' ?

findElement : It is used to find the first element in the current web-page.Only the matching value will be fetched.It returns a web-element from the page which is find in first attempt otherwise it throws an exception.
                    
findElements: It is used to find all the elements in the current web page. All the matching elements will be fetched and stores in the list of web-elements.It returns a list of web-elements from the page. It can return an empty list if no DOM elements match the query.

What are the different Browser specifications in Selenium web-driver?


  1. ChromeDriver()
  2. InternetExplorerDriver()
  3. AndroidDriver()
  4. IphoneDriver()
  5. FirefoxDriver()
  6. HTMlUnitDriver()
  7. RemotewebDriver()
  8. IphonesimulatorDriver()
  9. EventFiringWebDriver()

Out of all the available driver implementations HTMLUnit  Driver is the fastest one.
HTMLUnit Driver does not execute tests on browsers but on plain HTTP request response.
HTMLUnit is also called Headless browser driver.



Alerts in Selenium Web-driver.

There are 2 types of alerts in selenium web-driver.
  1. Web based alerts
  2. Windows based alerts
1.Web based alerts are handled by selenium but selenium cannot handle windows based alerts.
2. Selenium uses third party tool to handle windows based alerts.
3. They are Autoit, Sikuli, Robot class.
4. In selenium web-driver the web based alerts are handled by below methods.

  • void accept( ) - It clicks on OK button.
  • void dismiss( ) - It click on Cancel button.
  • String getText( ) - It returns text written on the web alert.
  • void sendKeys( )- It sends data into web alert.

What is 'Parametrization', 'Forward compatibility' and 'Backward compatibility' in Selenium web-driver?

  Parametrization
  1. Some-times to execute the test script we have to fetch the Test Data.
  2. This test data can be from xls or spread-sheet.
  3. So the process of reading the test data from external source like xls files  is called 'Parametrization'.
  Forward compatibility

  • Its the ability of selenium 1/RC to execute the scripts created in selenium web-driver.

 Backward compatibility

  • Its the ability of selenium web-driver to execute the scripts created in selenium 1/RC.

Reason for Integrating Selenium and Web-driver.

Selenium: 
Main Advantage: Supports wide range of browsers.
Web-Driver:
Main Advantage: Ability to bypass the Java-script sandbox. ( Server).

The main advantage of both were the main drawbacks of other.
This reason made both of them to integrate together and come up with a strong and powerful tool called 'Selenium Web-driver' or 'Selenium2'.

18 November, 2014

Limitations of Selenium Web-driver. ( Browser's Native Support)

Selenium web-drivers operates at Operating System Level.
Now, each browser communicates with its Operating System in its own way.
The way by which browsers communicates with the Operating System is called Browser's Native support or its is browser's built in support for automation.
When any new browser comes into market then we will have to give some time to selenium web-driver to understand the browser's native support.
So web-driver cannot readily support new browser.
HTMLUNIT and Firefox are the two browsers that web-driver can directly automate.
For other browsers it require Driver server.

Architecural Differences Between Selenium RC and Selenium Web-Driver.

Selenium RC Architecture
  1. No Direct communication between selenium Code and AUT.
  2. Their is a RC server which we have to Start/Stop before/After every execution.
  3. No Support for Android and i-phone.
  4. Cannot handle Rich API.
  5. Cannot handle mouse movements.
  6. When we start the selenium RC server it injects Java-script program called 'Selenium Core' into the browser.


Selenium RC Architecture 


  1. Their is no RC Server so we do not have Start/Stop it before/after every execution.
  2. Support for Android and i-phone.
  3. Can handle Rich API.
  4. Can handle Mouse Movements.
  5. Future enhancements are supported.

13 November, 2014

How to know in which iframe we are or whether the element is present in the source code or not?

Its very hard specially when we have nested iframes to know in which iframe we are currently working.
also the situation comes when we want to know whether the element is present in the source code we are currently pointing to.

By using Assertion we can easily know it.

Also remember if the Assertions fails the script will Stop and will not execute the steps after assertions.

  assertTrue(driver.getPageSource().contains("Text-you-are-Looking-for"));  


How to switch to the correct iframe when iframes do not have id or name?

When iframes do not have name,ids its very hard to identify them or switch to correct iframes.

Below is an example where we can understand the scenario in better way.

 Below  is an example where iframes do not have name,ids but you can easily notice that  both the iframes have  src with them.

we can use src to uniquely  identify and switch to the correct iframe.

To identify the correct iframe with src we can use below technique.

  driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@src,'CSPortalGuiWidgetSelector')]")));  




--------------------------------------------------------------------------------------------------------
<html>
<head>
<body>
<iframe scrolling="auto" frameborder="no" src="../admin?redirect=true&" marginwidth="0" marginheight="0">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="de-DE" dir="ltr" xml:lang="de-DE" xmlns="http://www.w3.org/1999/xhtml">
<head>
<body class="CSPortal Win ff17 ff SingleWidget SingleTab editmode" ffdragdropid="dd_1">
<div id="CSPortalPortalTitle" onclick="CS.reloadTopFrame();">Rupesh</div>
<div id="CSPortalPortalLogo" onclick="CS.reloadTopFrame();"></div>
<div id="header">
<div id="main" class="tabs1 t1 st0">
<div id="footer">
<div id="CSPortalWindow" class="CSPortalWindow" name="CSPortalWindow" style="width: 1000px; height: 568px; left: 20px; top: 20px; z-index: 10003;">
<div class="CSPortalWindowToolbar">
<div style="background-color: white; position: relative; overflow: auto; width: 1000px; font-size: 0px; height: 526px;">
<iframe frameborder="0" style="background-color: white; border: medium none; width: 100%; height: 100%; margin: 0px; padding: 0px;" src="../admin/portal.php?forward=core/extensions/portal/gui/framework/CSPortalGuiWidgetSelector.php&mode=add&PortalTabID=131&col=1">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html style="height:100%">
<head id="CSGuiWindowHead">
<body id="CSGuiWindowBody" class="Win ff17 ff hasHeight" oncontextmenu=";" style="background-color: #FFFFFF; height:100%;width: 100%;">
<div id="CSPortalLayoutManager_4367034" class="CSPortalGuiLayout">
<div class="CSPortalGuiLayoutInnerDiv">
<table class="CSPortalGuiLayout">
</tbody>
</table>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</td>

11 November, 2014

Introduction to Automation Testing

* What is Test Automation?

A simple and one line explanation is "Test Automation means using a software tool to run repeatable tests against the application under test.

* Advantages of Automation
 1. Repeatability of Tests.
 2. Speed at which tests can be executed.

* When not to implement Automation?
 1. Application's user interface is not stable or its about to change in the future.
 2. Not enough time to build test automation.i.e when the time for testing is very short its really hard to automate the project by writing a test scripts so manual approach is best.

* When Automation has to be implemented?
 1. Regression / Re-testing
 2. When a quick feedback is expected for Developers.
 3. If we want to unlimited iterations of Test cases.
 4. Finding defects missed by Manual Testing.

30 June, 2014

Access restriction on class due to restriction on required library rt.jar?

 Access restriction on class due to restriction on required library rt.jar?

The solution is to simply tell Eclipse that these aren't errors.

Below are the steps for the same.

In your Eclipse go to 
Windows -> Preferences -> Java -> Compiler -> Errors/Warnings -> Deprecated and restricted API -> Forbidden reference (access rules): -> change to warning

21 May, 2014

Unable to pass string using 'sendKeys()' method

Unable to pass string using 'sendKeys()' method



Java compiler is set to 1.5 version change it to 1.6.
This is a very common problem with the Java compiler. All you need to do is just set the Java compiler 1.6 from 1.5.
To change the Java compiler version, complete the following steps:
  1. In the Project Explorer view of the Java EE perspective, right-click the project and then select Properties.
  2. Select the Project Facets page in the in the Properties window. This page lists the facets in the project and their versions.
  3. Click Modify Project.
  4. Double click the version number next to the Java facet to select a different level of Java compiler.
  5. Click Finish to close the Modify Faceted Project window and then click OK.