Selenium with Java Example

Test automation requires a tool that can automate the application, a testing tool or library that provides various capabilities like – test result reports, a different type of validations, etc and a programming language which both these tools or libraries support.

In this example, we will use the following to test the Google Calculator feature-

  • Selenium WebDriver – For UI automation
  • TestNG – As a testing framework
  • Java – As a Programming language

Using all these, we will automate the Google Calculator feature on the Chrome browser. For running the test on the Chrome browser, we need to set the webdriver.chrome.driver system property and point to a chrome driver executable file-

  1. Download the latest ChromeDriver binary from Chromium.org download page and place the executable on your local machine.
  2. Set the webdriver.chrome.driver property to the chromeDriver.exe’s location as-
    System.setProperty(“webdriver.chrome.driver”, “chromeDriver.exe path”);

Now, let’s check the code snippet for this test. You can download this java file here calculatorTest.java.

public class calculatorTest {
	
	@Test
	//Tests google calculator
	public void googleCalculator(){
		
		//Creating a driver object referencing WebDriver 
		WebDriver driver;
         
		//Setting the webdriver.chrome.driver property to its executable's location
		System.setProperty("webdriver.chrome.driver", "/lib/chromedriver.exe");
		
		//Instantiating driver 
		driver = new ChromeDriver();

		//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");
	}
	
}


For complete step by step Selenium tutorial series, please check – Selenium WebDriver with Java Tutorial.

Leave a Comment