Selenium WebDriver Java example

selenium webdriver java exampleSelenium is a widely used test automation framework. It has APIS for many languages and Java is among them. In this short tutorial you will learn how to use its main class called WebDriver.

Why do we need Selenium WebDriver?

In Software Testing realm of any IT-project there’s a comprehensive part of regression testing. Selenium is used to automate this tests. So you won’t need a huge amount of human resources to support regression day-by-day.

Selenium WebDriver opens a real browser window and can interact with the DOM of any web-site you want. It is an efficient tool for quality assurance because it could be optimized by the time of test execution.

Selenium WebDriver Java example code

We will do a simple Selenium example in Java. It will open the main page of this blog and print out the its title. For this we will do:

  • create a new maven project
  • add Selenium dependency
  • create a class with main method and functionality

Let’s create a new maven project. You need to specify selenium dependency:

<dependency>
     <groupId>org.seleniumhq.selenium</groupId>
     <artifactId>selenium-java</artifactId>
     <version>2.48.2</version>
</dependency>

Now we can use WebDriver class in our code:

WebDriver driver = new FirefoxDriver();
driver.get("http://10minbasics.com");
System.out.println(driver.getTitle());
driver.close();

We instantiate the Firefox WebDriver but it is possible to run tests in Chrome and Internet Explorer.

driver.get() – is a method that opens a browser window and tries to load the specified page URL.

driver.getTitle() – returns a string containing the title of current page loaded by WebDriver.

driver.close() simply closes the WebDriver.

In the next chapters we will show the functionality for selecting elements and will cover the Page Object pattern.

For more information checkout the official documentation.

Leave a Reply

Be the First to Comment!