WebDriver is really a good clean and powerfull API to test the browsers. Obviously now Selenium 2.0 is backed by WebDriver and there are different options you can use webdriver in different way. (With and Without a Proxy server) But originally WebDriver came with an idea of talking to browsers natively to driver then to achieve faster and better response. How is it different from Selenium. Please see the post . So, I would focus on this post to write a simple Google search test using webdriver.
I am assuming you have got a basic Java project setup where you can write tests in Java, and also you can choose any unit testing framework of your choice. WebDriver is a generic interface which then gets implemented by different available drivers (browsers) to achieve the consistency in the API. However, there are still some difference between the drivers, but we will ignore that for this posts, as basic API is consistent across the driver. Having an interface independent of driver implementation helps to write driver independent tests, so we can write a test in WebDriver and run that against any available driver (Firefox, Chrome, IE and Iphone driver).
I must admit that chrome driver is little immature at the moment, but I am sure it should be good soon. For my example I will be using Eclipse as the IDE and TestNG as the unit testing framework.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package org.wd.tests; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.Test; import org.wd.annotation.DataDriven; public class TestGoogle{ /* This creates a field of type WebDriver Interface*/ protected WebDriver driver; @Test public void testGoogle(){ /*This will crate a new Instance of Firefox driver*/ this.driver = new FirefoxDriver(); /*This will launch www.google.co.uk on the browser*/ driver.get("http://www.google.co.uk"); /*Identify the elements to interact with */ WebElement searchTextBox = driver.findElement(By.name("q")); WebElement searchButton = driver.findElement(By.name("btnG")); /*Take actions now - Set the text field*/ searchTextBox.sendKeys("Pankaj Nakhat"); /*Click on the searchButton*/ searchButton.click(); /*Verify HTML response contains some text*/ Assert.assertEquals(driver.getPageSource(), "Pankaj Nakhat"); driver.quit(); } } |
