Selenium WebDriver with TestNG Sample Script


Selenium WebDriver with TestNG in Java - in this example, we will test the Google Calculator feature using Selenium for UI automation and TestNG as testing framework. You can download this java file here calculatorTest.java (right click on 'calculatorTest.java' and click on 'save link as...' to save the sample selenium test script).

public class calculatorTest {
	
	@Test
	//Tests google calculator
	public void googleCalculator(){
		
		//Create firfox driver's instance
		WebDriver driver = new FirefoxDriver();
		
		//Set implicit wait of 10 seconds
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		
		//Launch google
		driver.get("http://www.google.co.in");
		
		//Write 2+2 in google textbox
		WebElement googleTextBox = driver.findElement(By.id("gbqfq"));
		googleTextBox.sendKeys("2+2");
		
		//Click on searchButton
		WebElement searchButton = driver.findElement(By.id("gbqfb"));
		searchButton.click();
		
		//Get result from calculator
		WebElement calculatorTextBox = driver.findElement(By.id("cwos"));
		String result = calculatorTextBox.getText();
		
		//Verify that result of 2+2 is 4
		Assert.assertEquals(result, "4");
	}
	
}