Simple Selenium Webdriver Example in Java

After Setting up the environment we can now go ahead and write some sample code. We will be using Java for this purpose.

Take a look at the code example below and afterwards we will try to understand the working


import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SimpleExampleTest {
    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "https://www.google.co.in";
        driver.get(baseUrl);
    };

    @Test
    public void testSimpleExample() throws Exception {
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("selenium");
        element.submit();
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
              public Boolean apply(WebDriver d) {
                  return d.getTitle().equals("selenium - Google Search");
              }
          });
        driver.findElement(By.linkText("Selenium - Web Browser Automation")).click();
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
              public Boolean apply(WebDriver d) {
                  return d.getTitle().equals("Selenium - Web Browser Automation");
              }
          });
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }
}

Explaination

The above example searches for the text “selenium” in Google and clicks on of the search results. If the browser finally arrives to the right page (decided by the page title) we say the test is successful.

Annotations

For those who are not much familiar with the annotations the @Before makes sure that a method is called before every test, similarly @After makes sure that a method is always called after every test method which is denoted by @Test annotation. So the sequence in the above example will be: setUp() >> testSimpleExample() >> tearDown(). If we had another test method (say) testAdvancedExample then the order will be setUp() >> testSimpleExample() >> tearDown() >> setUp() >> testAdvancedExample() >> tearDown()

The setUp() method

This method initializes the driver and the baseUrl variables in first two lines and opens the web page pointed by thebaseUrl variable. The driver variable is initialized for the Firefox browser, so the test will be run on the Firefox. If the test is to be run on Google Chrome chromedriver executable should be downloaded and its path has be added to the PATH variable in the system. To programatically set the chromedriver path for individual scripts the following code can be used:

<pre><code>

System.setProperty(“webdriver.chrome.driver”, “path_to_chromedriver_dir\\chromedriver.exe”);
driver = new ChromeDriver();

</code></pre>

The testSimpleExample() method

As the name suggests this method is the actual test to be performed. Here is the line by line explanation:

  • The very first line of the method finds the element by the name given to it, in this case it is an input fields whose name is “q” and saves it to the element variable of class WebElement.
  • Next it submits the form(only since the element is inside the form element).
  • In the next line the script waits for 10 seconds by creating a WebDriverWait object. The driver waits for 10 seconds or until the the expected condition specified in the until() method is met. In this case the expected condition is to check the equality of the page title and the text “selenium – Google Search”. Which ever happens first either the 10 seconds time or the condition, the driver resumes the execution. Between this wait the driver on every 500 milliseconds check for the condition to be met. The wait is provided because the the browser may take time to get the search results based on the network connection speed.
  • Next it finds an element by its link text and clicks on it.
  • Once again a time wait is created to see if the browser has opened right page by matching its title witht the text “Selenium – Web Browser Automation”.
  • If any of the above conditions fails the test is said to have failed.

The tearDown() method

This method simply frees the resources held for the test, i.e., closes the browser by calling the driver.quit() method.To perform all the above interaction the Selenium API provides various methods to select the elements on the page. Take a look at various selection method on the Element Selection page.

Advertisements

One thought on “Simple Selenium Webdriver Example in Java

  1. Pingback: Setup Environment For Selenium | cubcode

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s