Tuesday, 19 July 2011

Example - Selenium 2.0 using WebDriver API

Aim:
Example to demonstrate Selenium 2.0 using Webdriver API, here are the aims of examples:

  1.  to setup the development environment - Eclipse , jUnit and Selenium 2
  2. to run and execute your first selenium 2 test script
  3. get a feel for the commands and execution on Eclipse



Difficulty Level: High

Exercise Execution Time: more details coming soon

Prerequisites:
  1. None - this example will demonstrate installation of all the executables
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, name, linkText and xpath
  • clear()
  • sendkeys()
  • click()
  • random string
Steps in implementation:
  1. Download and Install Eclipse IDE using link http://www.eclipse.org/downloads/
  2. Tip: download the version suitable for your PC ( 32 bit/64bit))
  3. Download the Selenium2 API 'selenium-server-standalone-*.jar' library using link http://seleniumhq.org/download
  4. No need to get JUnit jar file in separate as it is inbuilt in  'selenium-server-standalone-*.jar'.
  5. Launch the Eclipse IDE
  6. Create a new Java project and name it FirstExample. You will see a default folder 'src' inside it.
  7. Do right click on the created project and select Build Path >> Configuration Build Path
  8. Add 'selenium-server-standalone-*.jar' under Libraries tab by clicking 'Add External Jars'.
  9. Right click on 'src' and add a package 'com.example.tests'.
  10. Create two java classes  'addPost.java' and 'addUser.java' into the created package.
  11. Paste the below mentioned two script in corresponding java files.
  12. Right click 'addPost.java' and click 'Run as >> JUnit test'.
What does script simulate?
    1. login using username and password to foundation.time2test.co.uk wordpress portal
    2. click "posts"
    3. Click on "add new"
    4. enter details in form for new post like title,
    5. click on "publish"
    6. click on "users"
    7. enter details for new user in form
    8. click on add user
Java Files: Save as addPost.java
    package com.example.tests;
    
    import java.util.concurrent.TimeUnit;
    import org.junit.*;
    import static org.junit.Assert.*;
    import org.openqa.selenium.*;
    import org.openqa.selenium.firefox.FirefoxDriver;
    
    public class addPost {
    private WebDriver driver;
    // Initializing the parameters
    private String baseUrl="http://foundation.time2test.co.uk/";
    private StringBuffer verificationErrors = new StringBuffer();
    @Before
    public void setUp() throws Exception {
    // Initializing the driver that script would run the Firefox
    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }
    
    @Test
    public void testSelenium2Example() throws Exception {
    // opening the base URL using the driver's get command
    driver.get(baseUrl);
    // Login into the application using the valid credential
    driver.findElement(By.linkText("Log in")).click();
    driver.findElement(By.id("user_login")).clear();
    driver.findElement(By.id("user_login")).sendKeys("admin");
    driver.findElement(By.id("user_pass")).clear();
    driver.findElement(By.id("user_pass")).sendKeys("time4test");
    driver.findElement(By.id("wp-submit")).click();
    
    // Asserting if we have logged into the application or not
    for (int second = 0;; second++) {
    if (second >= 60) fail("timeout");
    try { if (isElementPresent(By.xpath("//div[@id='user_info']/p/a[2]"))) break; } catch (Exception e) {}
    Thread.sleep(1000);
    }
    
    // Clicking the Post link for adding a new post
    driver.findElement(By.linkText("Posts")).click();
    for (int second = 0;; second++) {
    if (second >= 60) fail("timeout");
    try { if (isElementPresent(By.xpath("//div[@id='wpbody-content']/div[3]/h2"))) break; } catch (Exception e) {}
    Thread.sleep(1000);
    }
    // Add a new post
    driver.findElement(By.linkText("Add New")).click();
    driver.findElement(By.id("title")).clear();
    driver.findElement(By.id("title")).sendKeys("MyPost New Post");
    driver.findElement(By.id("publish")).click();
    // calling a method for adding an user
    addUser se=new addUser();
    se.seleniumExample(driver);
    
    }
    
    @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;
    }
    }
    }
    
    
Save as addUser.java
    package com.example.tests;
    
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.*;
    import java.util.*;
    
    public class addUser {
    
    public void seleniumExample(WebDriver driver)
    {
    driver.findElement(By.linkText("Users")).click();
    // generating a random value
    driver.findElement(By.xpath("//li[@id='menu-users']/div[3]/ul/li[2]/a")).click();
    Random rand = new Random();
    int numNoRange = rand.nextInt();
    String userstr="TestNewUser"+numNoRange;
    String email="Testemail"+numNoRange+"@yahoo.com";
    driver.findElement(By.id("user_login")).clear();
    // Using the random values in adding a new user
    driver.findElement(By.id("user_login")).sendKeys(userstr);
    driver.findElement(By.id("email")).clear();
    driver.findElement(By.id("email")).sendKeys(email);
    // Adding an user
    driver.findElement(By.id("first_name")).clear();
    driver.findElement(By.id("first_name")).sendKeys("TestFirst");
    driver.findElement(By.id("last_name")).clear();
    driver.findElement(By.id("last_name")).sendKeys("TestLast");
    driver.findElement(By.id("url")).clear();
    driver.findElement(By.id("url")).sendKeys("http://www.google.com/");
    driver.findElement(By.id("pass1")).clear();
    driver.findElement(By.id("pass1")).sendKeys("time2test");
    driver.findElement(By.id("pass2")).clear();
    driver.findElement(By.id("pass2")).sendKeys("time2test");
    driver.findElement(By.id("addusersub")).click();
    }
    }
Helpful Video:

13 comments:

  1. I have used "pre class" tags with the uploaded codes but I don't know why I don't see the codes without downloading option.

    ReplyDelete
  2. One thing I noticed is a lot of url's for installation of various components.

    It would make my life so easier if we can have those links listed in each post that requires them, so I can quickly click on them rather than having to type.

    ReplyDelete
  3. I would like a more detailed description of how the project is created as I never used Eclipse or Java.

    ReplyDelete
  4. When I run this with the foundation.time2test.co.uk Wordpress site, the second script didn't run because the file "New Post1234" already existed. Once I changed the name of the post, then the script run succesfully.

    Can we have a java random number function to create a random post name like "New Post 7854" and replace the static name of 'New Post1234' ?

    ReplyDelete
  5. following needs to change:
    driver.get("http://localhost/wordpress/wp-login.php" needs to change to foundation.time2test.co.uk website

    ReplyDelete
  6. Viresh's questions for me regarding this exercise:
    1. what commands are we using in the example
    2. how to install the "devolopment enviornment" ?
    3. what does the example actually demonstrate?
    4. Do the steps reflect what is shown in the video?
    5. what versions of software are used?

    ReplyDelete
  7. Hi Viresh,

    Question1: what commands are we using in the example
    Answer:
    a. findelement by ID and LinkText
    b. Clear()
    c. sendkeys
    d. click

    Question2: how to install the "devolopment enviornment" ?
    a. Download and Install Eclipse IDE
    b. Download the Selenium2 jar files
    c. Launch the Eclipse IDE
    d. Create a new Java project
    e. Do right click on the created project and select Build Configuration path
    f. Include external jar files for Selenium2 API jars
    e. Create a new package say test
    f. Create two java file into it
    e. Paste the above two script in one to one
    g. Run the scripts using Selenium2

    Question3. what does the example actually demonstrate?
    Answer: Example demonstrate how actually we can start creating script using Selenium2 library command with using Web Driver.

    Question4 . Do the steps reflect what is shown in the video?
    Answer: YES

    Question5. what versions of software are used?
    Answer:
    Eclipse: 3.5
    Selenium2: 2.0.1

    thanks and regards,
    Vipin Gupta

    ReplyDelete
  8. I have updated the exercise as per your comment, please review and post the feedbacks here.

    ReplyDelete
  9. Vipin,

    This example seems to need Junit library, but not mentioned in pre requisites. Can you please add in the aforementioned list ?

    Thanks.

    ReplyDelete
  10. We are using Webdriver API so there is no need of JUnit library.

    ReplyDelete
  11. There are 3 JUnit annotations:

    1. @Test - This will let the framework know about each unit test.
    2. @Before - Whatever we write inside this block, it will be executed before each test.
    3. @After - Whatever we write inside this block, it will be executed after each test.

    ReplyDelete
  12. Instead of using driver.get(url) we can use driver.navigate().to(url)

    driver.navigate().back() will work as browser back button.
    driver.navigate.forward() will work as browser next button.

    ReplyDelete