Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Monday, May 23, 2016

WebDriver Explicit Wait: wait for element to load

If you want webdriver to wait for any element to be visible, we can use explicit wait. In simple way iof we use wait function for any given time, we can not make sure how muych time it will take to an element to get visible. Or if you give more time for wait, may be element gets visible early and un necessary your sript wait for the given time. So to manage this, we can use wait in diff way by creating instance variable of WebDriverWait class. This can be as below:

import org.openqa.selenium.By;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Test1 {

       public static void main(String[] args)
       {
             
              FirefoxDriver driver = new FirefoxDriver();
              driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //This is implicit wait used

              driver.get("http://vishalsachan.blogspot.in");
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.id("as_rst")));
        driver.findElement(By.id("as_rst")).click();
       }
}


In example above, script will wait only in that step  for 30 seconds or until element visible (whatever occurs first) and will move next step.

Monday, May 2, 2016

Handling Captcha in WebDriver

As definition itself says:
"A CAPTCHA is a program that  protects  websites against bots  by generating and grading tests that humans can pass but current computer programs cannot"

So these pages can't be automated fully. In fact Captcha itself is implemented to prevent automation. we can not completely automate the page having captcha.

While automation testing we can handle it by 3 ways as given below:
1- By disabling of captchas on test environments.

2- Hard code the captcha.
3- Handle by entering the captcha manually during execution.
 

3rd point can be done using below

WedriverPackage;

import java.util.Scanner;

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

public class HandlingCaptcha 

{    
        public static void main(String[] args)     
          {        
          
               WebDriver driver = new FirefoxDriver();        
               driver.get("https://www.irctc.co.in/");
               driver.findElement(By.id("usernameId")).sendKeys("vishal");
               driver.findElement(By.className("loginPassword")).sendKeys("vishal");  
               Scanner scan = new Scanner(System.in);
               System.out.println("Enter Captcha"); 
               String captcha = scan.nextLine(); 
               driver.findElement(By.className("loginCaptcha")).sendKeys(captcha);   
               driver.findElement(By.id("loginbutton")).click();    
           }
}



In case anyone has any other solution, or way to handle it, please share in comments. Thanks.


Thursday, April 28, 2016

Handling "Protected Mode" exception while launching IE using webdriver

When we try to launch IE using WebDriver on a very first time on a fresh computer, generally we get the below error:

Exception in thread "main" org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)

We can avoid this using DesiredCapabilities method. The code can be:

DesiredCapabilities DC = DesiredCapabilities.internetExplorer();
DC.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);

You can find more on this method here: DesiredCapabilities

So to run your test in IE browser here the complete code:

package WedriverPackage;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class crossBrowserTesting
{

    public static void main(String[] args)
    {
      
     DesiredCapabilities DC = DesiredCapabilities.internetExplorer();                                        DC.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
      
        System.setProperty("webdriver.ie.driver","C:\\IEDriverServer.exe");
        WebDriver driver = new InternetExplorerDriver(DC);
        driver.get("https://www.vishalsachan.blogspot.com/");
    }
}
 


Wednesday, April 27, 2016

Handling multiple windows in selenium 2.0 (webdriver)

Here I am trying to explain the concept of Handling Multiple windows in Selenium WebDriver. Selenium WebDriver has built in methods available to switch from one window to another window.
We will use :
WebDriver.getWindowHandles()
WebDriver.switchTo().window()

I am just pasting here the working code and that you can use in ur eclipse and try seeing how things works.

I am taking example of "www.timesjob.com" where you can click on links given in home page (top left side: ) to open multiple windows in webdriver.

I tried to explain the step by step action taken in code and hope this will help you understanding the code in better way.
---------------------------------------------------------------------------------------------------------------------------
import java.util.Set;

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

public class HandlingWindows
{

    public static void main(String[] args)
    {
          
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.timesjobs.com/");

/*below i m clicking to links given in home page which opening new windows*/

        driver.findElement(By.xpath("html/body/div[1]/div[3]/header/nav[1]/ul/li[2]/a")).click();
        driver.findElement(By.xpath("html/body/div[1]/div[3]/header/nav[1]/ul/li[3]/a")).click();
        driver.findElement(By.xpath("html/body/div[1]/div[3]/header/nav[1]/ul/li[4]/a")).click();

/*so till now webdriver has opened 4 windows, one parent and 3 child. Now here next statement printing the current url that is of parent window.*/

        System.out.println(driver.getCurrentUrl());

//Now using getWindowHandles method and get all handles of open window

        Set AllWindow= driver.getWindowHandles();
        String window1 = (String) AllWindow.toArray()[0];
        String window2=  (String) AllWindow.toArray()[1];
        String window3=  (String) AllWindow.toArray()[2];
        String window4=  (String) AllWindow.toArray()[3];


// Now here we can switch to any window using switchTo()

        driver.switchTo().window(window2);
        System.out.println(driver.getCurrentUrl());
/* I am just prinmting the URL to check if window is switching or not. here you can perform any operation in current focused window*/

        driver.switchTo().window(window3);
        System.out.println(driver.getCurrentUrl());

        driver.switchTo().window(window4);
        System.out.println(driver.getCurrentUrl());

        driver.switchTo().window(window1);
        System.out.println(driver.getCurrentUrl());
       
       driver.quit();
       
    }

}
---------------------------------------------------------------------------------------------------------------------
The output is :
http://www.timesjobs.com/
http://jobbuzz.timesjobs.com/
http://stepahead.timesjobs.com/
http://www.techgig.com/
http://www.timesjobs.com/

I hope this is simple way of learning the concept and now can try advance things.

Sunday, September 5, 2010

Configuring Selenium RC with TestNG using eclipse

Recently I was trying Selenium RC with TestNG using eclipse. I found it little tough without any proper step by step documentation. I took help of my collegues and completed. In fact I am not using this tool in my project but I always try to find time to work with selenium. After all you can not stop your learning :)
This tool is pretty good and rapidly taking place in market.

Any way I had successfully ran a sample test case using TestNG in eclipse with selenium RC. While it was starting but decided to post one article on “Configuring Selenium RC with TestNg using eclipse” to help testers those who want to start with same. I also maintain my blog as a database for self reference. So if you find it beneficial for you, you can write few words and if not then you can ignore :(



Finally here, step by step process to configure and run your first java test using TestNG and selenium RC in eclipse

1- Install JRE http://www.java.com/en/download/
2- Download eclipse http://www.eclipse.org/downloads/
3- Download TestNG http://testng.org/testng-5.14.zip
4- Download selenium RC http://seleniumhq.org/download/
5- Launch you eclipse

The workspace, you can select any working directory. In my case it’s “Selenium_Project”


Now clicking on Ok button, it will launch eclipse.




6- Install TestNG plugin

Go to help->install new software






Click on add. This will open a small window where you need to put location “http://beust.com/eclipse”.

Click on OK. You will see that an entry is added there. Now tick that box and click on next.



7- Add project

Click File->new->Java project

Give project name and finish


 

 
This will create project “MyProject”




8- Add TestNG jar to library

Select MyProject and then Go to (menu bar) project->properties->Java build path->Libraries



Click on add external JARs and add TestNG jar file (testng-5.14.jar) from folder which you get after downloading TestNG in step#3.



9- Add Selenium RC jar to library

Add selenium Jar file same way we have added testNG jar. Selenium jar file can be found in the “selenium-java-client-driver-1.0.1” folder which you get after downloading it in step#4.





10- Add Class file

In MyProjectt right click on scr folder then new->class


Name the class (e.g Login) and finish.


Now add your test code here under this class. As in my previous article I had mentioned that you can simply record your test using IDE and pick java code and use here. For more detail refer : http://vishalsachan.blogspot.com/2010/06/hi-folks-sorry-for-bieng-inactive-from.html



11- Run test

Run your clas file as TestNG





Ohh i forget one step here. before executing test/running class file you need to start selenium server. thia is similar to every time so i am just copying it from my previous article.



To start the selenium test server, first go to the location where your JRE is placed. For example
C:\Program Files\Java\jre6\bin\
and then Run the command java -jar selenium-server.jar
here it is supposed that you have placed your selenium -server.jar file in same location. In case if you have placed it in other location you can run it in following way:

C:\Program Files\Java\jre6\bin\java -jar jar “E:\SELENIUM\selenium-remote-control-1.0-beta-1\selenium-server-1.0-beta-1\selenium-server.jar”

This will start you selenium server.


Thanks.
 

Thursday, July 1, 2010

Selenium IDE: Use XPath if no id found in elemnet you want to work with

If you are working with IDE and recording your script. There may be some cases where you IDE can not record the action to the element that do not have any id. In such case you need to find the id manually and provide it to the script to cover your action. XPath help you here to navigate your site.

In one of my project when I was recording my script for create a post, I found that IDE is unable to record the text box activity. Actually that text box was Javascript content editor 'Tinymce' . Later I recognized that IDE is unable to find this editor as there was no label used for this. So I used X paths to locate the element ID. It looks like..
id('commentBodyField')

The XPath can be found using the Firefox plug-in. https://addons.mozilla.org/firefox/addon/1095
to find the XPath just right click over the desired element and click on view Xpath.

Monday, June 14, 2010

Testing web application using Selenium RC with eclipse

Hi Folks , sorry for bieng inactive from last few months. I was really busy these days. I respect all of yours comments and query. In fact I am not working with Selenium now but as you people asked me some queries on Selenium RC with eclipse in one of my previous article http://vishalsachan.blogspot.com/2009/09/using-selenium-rc-in-your-java-project.html

I am planing to write a use full article here where I will cover end-to-end testing your web application using Selenium in Eclipse. This is infact a detail version of my prev article mentioned above.

As said earlier I am not in touch with Selenium i.e I am not using this currently, so I will try my best to use my memory and old days 'R and D' to get it completed with high quality and quantity. Huaaaa

Here I will start with selenium IDE but will not go in detail as asuming that you people are comfirtable with IDE part. If you need any help in IDE then you can refer to other articles in this blog only.

Record and save you java script
1- Open Firefox and enter the URl to browse your application
2- Launch IDE from Tool menu.
3- Record your script
4- Choose the programing language as JAVA and save your script. To chose the language go to Option-> Clipboard formate and select Java-Selenium RC

Now you have a java code saved in your disk. I am making it simple and not covering scripting in detail. My motive is to teach you the end to end process of using this IDE and RC to run a simple test using Eclipse. Rest You can change your script as per your need.
Now we have ur test with us.
The next step is to open your eclipse and create a project.

1- Creating you java project in eclipse
The fiste stpe in eclipse is to create/add your project. To do this follow the steps below:
   -> Launch Eclipse
   -> Creat a java project named TestProject (for example)

2- Add Junit Library to your project
The next step is to add Junit Liabraries which consiste of following steps: 
  ->  Go to Project Properties
  ->  Go to Java Build Path
  ->  Click on Libraries tab
  ->  Click on 'Add Library' button
  ->  Select 'Junit' option from list and click on next
  ->  Select version 'Junit4' from drop down and click on finish.

4-Add Selenium Java Client Jar into Project:-
Once you added the java liabraries , the next step is to add selenium jar file. you can find it under selenium-remote-control-1.0-beta-1\selenium-java-client-driver-1.0-beta-1 folder what you have downloaded from

http://selenium-rc.openqa.org/download.html

To add this Jar file follow the below steps:
  ->  Go to Project Properties
  ->  Go to Java Build Path
  ->  Click on Libraries tab
  ->  Click on 'Add External Jars'  button
  ->  Browse and add the 'selenium-java-client-driver.jar' from the sourse where you had saved it.

5- Initiating the Selenium Test Server
To start the selenium test server, first go to the location where your JRE is placed. For example
C:\Program Files\Java\jre6\bin\
and then Run the command java -jar selenium-server.jar
here it is supposed that you have placed your selenium -erver.jar file in same location. In case if you have placed it in other location you can run it in following way:

C:\Program Files\Java\jre6\bin\java -jar jar “E:\SELENIUM\selenium-remote-control-1.0-beta-1\selenium-server-1.0-beta-1\selenium-server.jar”

This will start you selenium server.

6- Adding your test (Java class )  in our Project
To add you test (which you have saved earlier) as a java class file to the project (TestProject, already saved) follow the steps:
 ->  In eclipse go to create a new java class
 ->  Create it with name MyFirstTestCase (for example) and paste the code from the file u had saved it
 ->  Choose "com.thoughtworks.selenium.SeleneseTestCase" as its super class
 ->  Finish it

7- Modifying your test script (java class)
Once you are done with ur class file, it will look like,

Package.*
import com.thoughtworks.selenium.SeleneseTestCase ;
public class MyFirstTestCase extends SeleneseTestCases {
      public void setUp() throws Exception {
            setUp( " http://vishalsachan.blogspot.com/ " , "*firefox'); }

............ You test script..............
}

In case you want to run this in diff browser then simply you can change your script
setUp( " http://vishalsachan.blogspot.com " , "*firefox'); to setUp( " http://vishalsachan.blogspot.com " , "*chrome'); or whatever browser you need to run wid.

8- Running your test
Finally we are ready to tun our first test. To run this in eclipse you click on Run button
select option Run as "JUnit Test'

Ohh ya one thing I forgot to mention that if you  have eclipse with JRE version lower than 1.5 in Build Path
then might be the case when you run the test , it will show some error related to version not suporting. so for this remove the default Eclipse JRE and add JRE version 1.5 or mor to System Library in Build Path.
To add this follow the steps:
-> Go to Java Build path and select Libraries tab
-> Under this select JRE system Library
-> Remove your default one
-> Now click on add Library and select JRE system Library and click next
-> Add JRE
-> Now add this JRE to your class path

So finally I am done with your end to end execution of ur java test using selenium RC in eclipse. Thanks.

Friday, September 4, 2009

using selenium RC in your java project - How to run your script in different browser

I have been using selenium IDE fro last 1 year or so. In fact I just use this to automate few of our module. I was not so active user of selenium in this period.
Few months back my company placed me in a java project. I wanted to work with some automation tool not exactly play back and recording. There for I tried my hand in selenium RC. Recently I successfully managed to install RC with eclipse (Java IDE used in my project) and ran some of test case recorded in IDE. I am trying my hand to make them data driven and more specific. For that one should be good in java programming. I am also trying to be good in that.

I have seen many of us seeking help to configure RC in their project. All they want to run very first test case. for that, I decided to write some thing which may help to begin with the very first etst case in RC.
Here in my article I will explain how to configure RC with eclipse and how to run the test case recorded in IDE.
I am assuming that you are good in using IDE record and playback.
So once you done your recording with IDE convert your recorded script in java. for this click on OPTIONS->FORMAT and choose java. save this test case as simple java file.

so you have your test case say test.java.

Now follow the steps to configure Rc and java client driver with eclipse.

1- Download Selenium-RC from the SeleniumHQ downloads page and save this some where you want.

2- launch eclipse
3- Create a new java project (I guess you are aware of creating a new project in eclipse. If not then take help from developer or visit documentation section in http://seleniumhq.org/)
4- Add external jar files. (from the location where you have already saved downloaded selenium rc)
5- Add your saved java file(which you have saved after recording in IDE) to this project
6- Now run this as Junit test


here I am giving some explanation which might help you to get the things easily.


This is the java code which i have recorded using IDE to test the search in Google.

import junit.framework.*;
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;

import com.thoughtworks.selenium.SeleneseTestCase;
public class test1 extends SeleneseTestCase {

public void setUp() throws Exception {
setUp("http://www.google.co.in/", "*firefox");
}
public void testVishal() throws Exception {
selenium.open("/");
selenium.type("q", "vishal sachan");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
verifyTrue(selenium.isTextPresent("vishal sachan"));
}

}

Running your test in multiple browser:
You can now run this test in different browse by initializing the desired browser info like firefox, iexplorer, chrome..
setUp("http://www.google.co.in/", "*firefox") ;

I hope this will help you to get started with you very first test using selenium RC.