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 that both these tools or libraries support.

In this Selenium with Java 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 system property and point to a chrome driver executable file.

  1. Download the latest ChromeDriver binary from the download page and place the executable on your local machine.

  2. Set the property to the chromeDriver.exe’s location as-
    System.setProperty(“”, “chromeDriver.exe path”);

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

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

		//Set implicit wait of 10 seconds
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
		//Launch google
		//Write 2+2 in google textbox
		WebElement googleTextBox = driver.findElement("gbqfq"));
		//Click on searchButton
		WebElement searchButton = driver.findElement("gbqfb"));;
		//Get result from calculator
		WebElement calculatorTextBox = driver.findElement("cwos"));
		String result = calculatorTextBox.getText();
		//Verify that result of 2+2 is 4
		Assert.assertEquals(result, "4");

This completes our tutorial on – Selenium with Java example. For a complete step-by-step Selenium tutorial series, please check – Selenium WebDriver with Java Tutorial.

Leave a Comment