Jan 22, 2013

Starting to use Selenium Webdriver


For a long time I used the Selenium IDE and RC for web system testing. Using java platform, it was possible to build robust test suites and generate automatic reports using Junit.
Like last year I have been worked in systems for mobile devices, I had not yet experienced the successor of Selenium RC, the Selenium Webdriver.

Selenium webdriver is a tool designed to provide a simple interface and a concise programming to better support dynamics web pages.

In my research about Selenium Webdriver, I found a interesting comparison table that I show bellow. It can help to understand the differences between Selenium RC and Webdriver.


Selenium IDESelenium RCWebdriver
Works only on mozillaWorks on almost all browsers.Does not work on latest version of firefox/IEWorks on latest versions of almost all browsers - Firefox, IE(6,7,8), OPera, Chrome
Record and run toolNo Record and runNo Record and run
No server required to startServer is required to startNo server required to start
Core engine is Javascript basedCore engine is Javascript basedInteracts natively with browser application
Very simple to use. If using User extentoins, you require knowledge on javascript which makes the work a little bit tough.Its a simple and small APIComplex and a bit large API as compared to RC
Not at all object orientedLess Object orinted APIPurely Object oriented API
Cannot move mouse with itCannot move mouse with itCan move mouse cursor
Full xpaths have to be appended with 'xapth=\\' syntaxFull xpaths have to be appended with 'xapth=\\' syntaxNo need to append 'xpath=\\'
No ListenersNo ListenersImplementation of Listeners is provided
Cannot test iphone/Android applicationsCannot test iphone/Android applicationsCan test iphone/Android applications


source: http://qtpselenium.com/selenium-tutorial/difference-between-ide-rc-webdriver/


I found very interesting the following points:

  1. In Selenium Webdriver is not necessary to initialize the RC server.
  2. It is not necessary to use XPath.
  3. Fully object oriented.
  4. You can move the cursor.
  5. Can test on iphone and android applicat

For these reasons I decided to try the Selenium Webdriver.

I will describe my first example:

Installation and Configuration

  1. In Selenium page http://code.google.com/p/selenium/downloads/list  download the following  files: selenium-server-standalone.jar, selenium-java-2.29.0.zip , and the browser drivers : IEDriverServer_x64_2.29.0.zip and chromedriver_win_23.0.1240.0.zip .
  1. Open the Eclipse newest java version.
  2. Create a Java Project . File -> New -> Java Project
  3. Choose a  name for your  project,  SeleniumTest for example.
  4. The new project will appears in the package explorer.
  5. Select the project created in the package explorer and click using right mouse button.
  6. Create a new folder : New -> Folder
  7. The name of new folder is lib.
  8. Extract the selenium-java-2.29.0.zip and copy selenium-server-standalone.jar to inside the new folder lib.
  9. Select the jars and click using right mouse button and select Buildpath -> Add to Build Path.
  10. The IEDriver and Chromerdriver must be stored in a folder in the C:\BrowserDrivers.

Fast Example


Let's try to test the login page of testlink demo.

  1. Open the firefox and Install the Selenium IDE (http://seleniumhq.org/download/). 
  2. After Install the Selenium IDE, start it in Firefox -> Web Developer -> Selenium IDE.
  3. The Selenium IDE will open and start to record the actions in the browser.
  4. In firefox start open the page  of testlink demo  http://demo.testlink.org/tl194demo/login.php.
  5. In the Login Name enter: admin 
  6. Password enter: admin
  7. The testlink home page will appears.
  8. Stop the Selenium IDE record.
  9. In the Selenium IDE window, save the test in File-> Export As -> Java /JUnit 4/ webdriver.
  10. save the file with the name Login.java in a folder.
  11. Go to Eclipse IDE
  12. Select the src folder in your java project created .
  13. Create a class using right click and select New -> Class
  14. The name of the Class is: TestLogin
  15. Open your test recorded Login.java, copy the content and paste in the eclipse TestLogin class. Bellow the class example.

package example;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class TestLogin {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Before
  public void setUp() throws Exception {
    driver = new FirefoxDriver();
    baseUrl = "http://demo.testlink.org/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testEWebdriver() throws Exception {
    driver.get(baseUrl + "/tl194demo/login.php");
    driver.findElement(By.id("login")).clear();
    driver.findElement(By.id("login")).sendKeys("admin");
    driver.findElement(By.name("tl_password")).clear();
    driver.findElement(By.name("tl_password")).sendKeys("admin");
    driver.findElement(By.name("login_submit")).click();
  }

  @After
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alert.getText();
    } finally {
      acceptNextAlert = true;
    }
  }
}

  1. Fix the package name errors and the name of the class.
  2. In eclipse package explorer select TestLogin.java with mouse right click and Run As -> JUnit
  3. The Login recorded will run.

Adjusts

One of the resources of Selenium webdriver is run the same test for more than one web browsers. Some adjusts in our first example test is required.


  1. First create more two drivers variables :  private WebDriver driver1, driver2, driver3;
  2. In the setUp() method replace for the following code:
   driver1 = new FirefoxDriver();
  driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
File file1 = new File("C:/BrowserDrivers/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file1.getAbsolutePath());
driver2 = new InternetExplorerDriver();
driver2.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
File file2 = new File("C:/BrowserDrivers/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file2.getAbsolutePath());
driver3 = new ChromeDriver();
driver3.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                
  baseUrl = "http://demo.testlink.org/";


To run my test was necessary to include the browser driver address in the computer (File file1 = new File("C:/BrowserDrivers/IEDriverServer.exe");) to start the IE browser and Chrome browser.

Change your test code adding the tests for each browser. See bellow:

 @Test
 public void testLoginFirefox() throws Exception {
 
 driver1.get(baseUrl + "/tl194demo/login.php");
     login(driver1);
 }
 
 @Test
 public void testLoginIE() throws Exception {
 
 driver2.get(baseUrl + "/tl194demo/login.php");
 login(driver2);
 }
 
 @Test
 public void testLoginChrome() throws Exception {
 
 driver3.get(baseUrl + "/tl194demo/login.php");
 login(driver3);
 }
 public void login(WebDriver driver){
 
 driver.findElement(By.id("login")).clear();
 driver.findElement(By.id("login")).sendKeys("admin");
 driver.findElement(By.name("tl_password")).clear();
 driver.findElement(By.name("tl_password")).sendKeys("admin");
 driver.findElement(By.name("login_submit")).click();
}
@After
 public void tearDown() throws Exception {
   driver1.quit();
   driver2.quit();
   driver3.quit();
   String verificationErrorString = verificationErrors.toString();
   if (!"".equals(verificationErrorString)) {
     fail(verificationErrorString);
   }
 }

All drivers must be closed using driver.quit() function.

Save the changes and Run the TestLogin.java again.
Run As -> JUnit.

As result the Login test will be executed for 3 browsers: Firefox, IE and Chrome browsers.

There's no need to start the Selenium server before the tests and without effort it was possible to run tests for  different kind of browsers.

I will try to test using resources for mouse cursor moving and I will post here the results.

Bye.

4 comments:

  1. Hello Sumit,

    I've been using Selenium with JAVA because it is the language we use in projects in my company. Java has a lot of tools to build reports and tools to be integrated with development environment thats the reason of a lot of testers are using Selenium with Java in Brazil. I think using the same language that programmers also allows them to collaborate with the automation environment during the project. But the Selenium can be used with script languages also. The most important is to know how to use the language tools and resources to build an automated test suite effective and easy to be used for the project team. About the course of Wizq, I don't know the course, the description seems interesting for Selenium begginers. It's good to know Java and Eclipse resources and tools to integrate Selenium and you will have grounding to apply the concept in other language platform.
    I hope I have helped you and thank you for your comment and for visiting the blog!
    Bye.

    ReplyDelete
  2. Hi There, Very helpfull tutorial, I have also recently created a blog about Selenium Automation that I am sure you will find really helpfull. Please visit
    http://seleniumregressionproject.blogspot.co.uk/

    ReplyDelete
  3. Thank you Mohammed Imran!!! Very nace your blog! I will try your tutorial for screenshots! :D

    ReplyDelete
  4. It's really a very good tutorial for the beginner. Thanks.

    ReplyDelete