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.

1 thought on “Selenium with Java Example”

  1. package testCases;

    import org.junit.Assert;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;

    public class superCalculatror {

    public static void main(String[] args) {

    // Read chrome driver exe
    System.setProperty(“”, “src/test/resources/drivers/chromedriver.exe”);

    // Open browser chrome
    WebDriver driver = new ChromeDriver();

    // Maximize browser

    // Open url

    //Fill number1

    //Fill number2

    //Click on Go!button

    //Result is displayed

    // sum = driver.findElement(By.xpath(“//h2[contains(text(),’15’)]”)).getText();
    Assert.assertEquals(driver.findElement(By.xpath(“//h2[contains(text(),’15’)]”)).getText(), “15”);

    //Close browser





Leave a Comment