Selenium with Java Example

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 webdriver.chrome.driver system property and point to a chrome driver executable file.

  1. Download the latest ChromeDriver binary from the 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 also 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");
}

}

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.

От QA genius

Adblock
detector