Running Selenium Tests on Chrome – Selenium Framework, Java

In this Selenium Framework Java-based guide, we will learn- How to run Selenium tests on Chrome browser? As, we know- What is Selenium, How to do setups, and start with Selenium? Now, we will run Selenium Tests on web browsers. So, Let’s get started –

A beginner's guide to Selenium Framework with Java.


Pre-requisites for this Guide

To follow this guide further, you should verify the required things first –

  • Core setup for Selenium framework,
  • Installed Web Browser (Chrome),
  • Download and place the ChromeDriver binary in your project,
  • Active internet connection.

To run Selenium tests on Chrome browser using Java, you first need the ChromeDriver binary file. Once you’ve downloaded the latest released ZIP file from the above official download link, you need to place it in your project.

To place the binary ChromeDriver file in your project, just follow the below step by step instructions for successfully running selenium tests on Chrome browser –

 

To Set Chrome Driver in Project, Right Click on Project Name > Create New Folder > Paste the ChromeDriver Binary

Running Selenium Tests on Chrome Browser with Java

What we want to do is, we want to write Selenium test scripts that will open up the Chrome browser > Writes some text in the Google Search box > Searches for that Query and Display us the Google results page by our ‘Selenium Test Script’.

So, to interact with Chrome or any other browser, we need to take help of something called Web browser drivers. These drivers are basically pre-written code and are mediators between any third-party user and the browser itself.

Using the driver, we can easily perform different actions on browsers and web pages such as- Opening the browser, Going to a webpage, Entering text in a Search box, etc.

The Selenium Framework provides us a driver for working with Chrome. And, that’s a Java class ChromeDriver. So, let’s see how to use that –

package com.shubhamklogic.selenium.browsertesting;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserTesting {

    public static void main(String[] args) {

        testOnChrome();

    }

    public static void testOnChrome() {

        String projectsPath = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.driver", projectsPath + "/TheDrivers/chromedriver.exe");


        WebDriver theDriver = new ChromeDriver();
        theDriver.get("https://google.com/");


        theDriver.close();
    }

}

In the above script, we used the Selenium’ ChromeDriver  class from the package org.openqa.selenium.chrome

 

Steps and Logic Behind the Code :

What we are doing in above code is –

@Line 2-3: We imported the required classes from Selenium library packages.

@Line 15-16: First we called the System.getProperty method to get user’s working directory in which the project is currently placed. Then we set the path to our Chrome Driver binary file using the System.setProperty method on the key webdriver.chrome.driver

@Line 19: We are creating an object of ChromeDriver , that has methods to perform automated actions on Chrome browser.

@Line 20: We invoked the get(“…”) method of theDriver object by passing the required URL as a String.

The get method will open the Chrome browser, Go to the given URL i.e. https://google.com/ and display us the Google page.


Facing Issues? Try these solutions :

Error 1 :

Exception in thread "main" java.lang.IllegalStateException: The driver executable does not exist: D:\EclipseProjects\SeleniumFrameworkJavaProject\TheDriver\chromedriver.exe
	at com.google.common.base.Preconditions.checkState(Preconditions.java:585)
	at org.openqa.selenium.remote.service.DriverService.checkExecutable(DriverService.java:146)
	at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:141)
	at org.openqa.selenium.chrome.ChromeDriverService.access$00(ChromeDriverService.java:35)
	at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExecutable(ChromeDriverService.java:159)
	at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:355)
	at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:94)
	at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
	at com.shubhamklogic.selenium.browsertesting.BrowserTesting.testOnChrome(BrowserTesting.java:20)
	at com.shubhamklogic.selenium.browsertesting.BrowserTesting.main(BrowserTesting.java:10)

If you are facing similar Exceptions, try these solutions –

Reason – One of the reasons for getting the above Exception is that, the wrong path to the chrome driver. As you can see in above screengrabs, we created a separate folder/directory named TheDrivers to keep all custom used drivers, but if we provide the invalid path to the System environment, we will get this exception.

Solutions – To resolve this exception, Re-analyse the path to the driver and put the correct name and slashes according to the Operating system.

  • If you are working on a Windows / Linux machine, then you can place the forward-slash / up to the driver name.
  • If you’re working on Mac machines, then just mention the path up to the directory containing the driver. There is no need to go till the driver name for these systems.

In order to fix the above error/exception, we need to replace TheDriver with the correct directory name TheDrivers.

 

Error 2 :
Another very common problem occurs with the incompatible versions of Web browsers and the Drivers. You might face errors such as Unable to start the chrome driver.

To resolve these issues, you need to replace your current using driver with a Latest or previous stable release. If you are facing issues with a chrome driver, then go to the Selenium Binding and Plugin releases page to download stable ChromeDriver for macOS / Linux / Windows.


Next steps : Inspecting Web Elements in Chrome

So far, we have successfully opened the Chrome browser, and go to the Google.com using Selenium scripts. Now, we need to type some text into the Google Search’s Input box, and perform the test on Google search.

For that, first, we need to find out –

1) What that element is?
2) What are its attributes? and
3) How can we Target/Locate them to test their functionality in Chrome.

With Selenium framework and Java, you can easily target Web elements of any web page, but before that first, you need to Inspect it to know the above 3 things.

To Inspect an element, just right-click on it and click on the last option “Inspect“. It will open the browsers developer tool, and display you the document containing

To run test on chrome with Selenium, first inspect the element and locate it with Test script

As you can see from the above illustration, it’s an HTML input element, and you can locate it by analyzing some of its key attributes –

<input class="gLFyf gsfi" jsaction="paste:puy29d;" maxlength="2048"
       name="q" type="text" aria-autocomplete="both" aria-haspopup="false" autocapitalize="off" autocomplete="off"
       autocorrect="off" autofocus="" role="combobox" spellcheck="false" title="Search" value="" aria-label="Search"
       data-ved="0ahUKEwiLof7el6_wAhXljuYKHXhsBjIQ39UDCAQ"><br>

Locating – Web Elements & Running Selenium Tests

So far, you have inspected the element on the Webpage. Now, to perform operations (such as typing and clicking) on it, first, you need to locate it. And, here are some of the ways to locate a Web element and perform Selenium tests on it –

  • class name : With class  attribute, you can locate elements whose class name contains the search value (but remember, compound class names are not allowed)
  • css selector : Locates elements matching a CSS selector
  • id : With id  attribute, you can locate elements whose ID attribute matches the search value
  • name : Locates elements whose name  attribute matches the search value
  • Link text : Locates anchor elements whose visible text matches the search value
  • Partial link text : Locates anchor elements whose visible text contains the search value. If multiple elements are matching, only the first one will be selected.
  • Tag name : Locates elements whose tag name matches the search value
  • xpath : Locates elements matching an XPath expression

Moving ahead with the above Google Search’s Input box example, we can locate it using the name attribute. As you can see, at this point, the name of that input element is “q“.

To locate that input element with Selenium, we will take the help of the Selenium Chrome driver’s findElement(..) method. This method takes an argument of type By. The By class provides a mechanism that is used to locate elements within a document.

By class have multiple static methods for locating elements, such as –

  • className ( String className ) : Returns By
  • cssSelector ( String cssSelector ) : Returns By
  • id ( String id ) : Returns By
  • linkText ( String linkText ) : Returns By
  • name ( String name ) : Returns By
  • partialLink ( String partialLinkText ) : Returns By
  • tagName ( String tagName ) : Returns By
  • xPath ( String xPath ) : Returns By

In the above Google input box’ example, we have picked the name locator, so we will have to use By.name( .. ) method to access that WebElement with Selenium –

WebDriver theDriver = new ChromeDriver();
theDriver.get("https://google.com/");
		
WebElement theElement = theDriver.findElement( By.name( "q" ));

Entering Keys – in Input Box Web Element :

So far, we have grabbed the Input box Web element having name=”q”. Now, to enter some text into that textbox, we can use the sendKeys(..) non-static method of the class WebElement.

The sendKeys(..) method provides the simulation of typing into the input element. Whatever you want to type in the input box, just pass the String message. You can also apply the pressable keys on the sendKeys(..)  method using the Keys enum.

For example : Google Search Box

In the above scenario of Google Search’s Input box example, we want to type some text into the input box and perform the keyboard’s Enter key operation after typing. To pass the characters and other keyboard’s operations, we can use the method sendKeys(..) like this –

theElement.sendKeys( "Wikipedia - Selenium" ); 
theElement.sendKeys( Keys.ENTER );

Summarizing All Together

Let’s summarize what we have done so far. First, we created a Selenium Framework Java Project and included the Chrome driver. After setting the path to the driver, we inspected and located the Web element in Chrome browser. Finally, we took help of sendKeys(..)  method, we passed a string query and performed the Search operation on Google.

Here’s the complete Selenium test script for Chrome browser –

package com.shubhamklogic.selenium.browsertesting;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class BrowserTesting {

    public static void main(String[] args) {

        testOnChrome();

    }

    public static void testOnChrome() {

        String projectsPath = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.driver", projectsPath + "/TheDrivers/chromedriver.exe");


        WebDriver theDriver = new ChromeDriver();
        theDriver.get("https://google.com/");

        WebElement theElement = theDriver.findElement(By.name("q"));

        theElement.sendKeys("Wikipedia - Selenium");

        theElement.sendKeys(Keys.ENTER);

        // To keep the Browser window open for 2 seconds -
        try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }

        theDriver.close();
    }
}

 

When you will run the above Selenium test script, it will open the chrome browser, go to https://google.com, typed “Wikipedia – Selenium” and fires the query on google by pressing the Enter key on keyboard virtually.

After all this, the browser will remain open for 2 seconds and then it’ll automatically be closed. This is how, we successfully tested the functionality of Google Search’s Input box on a chrome browser using Selenium framework and Java.

Hope this guide helped you to understand Selenium framework and Run Selenium Tests on Chrome browsers. If you’ve any doubt or issue, drop them in comments section below. I’ll try to solve your issues within a day. And, don’t forget to share the guide with your colleagues. It’ll help everyone to Automate the web on the fly.

Leave a Comment