TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Selenium Grid Webdriver Code Example
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Selenium Tutorial

Selenium Grid Webdriver Code Example

Last updated: Feb 25, 2024 10:43 am
By Meenakshi Agarwal
Share
10 Min Read
Selenium Grid Webdriver Code in Java
Selenium Grid Webdriver Code in Java
SHARE

In our earlier post on Selenium Grid, we explained an easier method to download and install the Selenium Grid. Also, the post did teach you how to configure multiple browsers like Firefox, Chrome, and IE with Selenium Grid. In today’s tutorial, you’ll get to learn how to run parallel tests with Selenium Grid Webdriver. And since we’ll create a multi-node setup in this post using Grid and Remote Webdriver, which can even help in using Selenium for load testing.

Contents
1- Writing Selenium Grid Webdriver Code using TestNG in Java.Step-1:Step-2:Step-3:Step-4:Step-5:Step-6:2- Test Execution.Step-1:Step-2:3- Result Analysis.Step-1:Step-2:Step-3:

We’ll give you the best approach to speed up test execution using Selenium Grid. We’ll make sure you should be able to set up and test, so we’ll try to keep things simple throughout the post. Also, we’ll provide a fully working Selenium Grid Webdriver code in Java which you can easily run in the Eclipse IDE. If you are a newbie in automation and want to learn Selenium Grid Webdriver, then just go through the step-by-step process of building a Selenium Webdriver project in Eclipse. It’ll help in ramping up quickly.

You would be amazed to know that even companies like Saucelabs and BrowserStack are making use of Selenium for load testing. They are using vast cloud infrastructure and customized Selenium to scale browser automation and load testing. Just imagine that together they are supporting 1000+ browsers and devices for testing using Selenium.

Selenium Grid Webdriver Code Example in Java.

Before we jump to the code section, it’s important for you to understand the use case we’ll cover using the Selenium Grid Webdriver code. In this tutorial, we’ll access a website that does the arithmetic calculations. So, the Selenium Grid Webdriver code will start the three browsers in parallel. Then, it’ll open the web page and process the calculation request at the same time in all three browsers. However, the operation will end up fast. But you would perceive the difference as the Selenium Grid will speed up the tests by running them in parallel.

With Selenium Grid, you not only speed up the test execution but also make it do the cross-browser testing. That’s the way you can ensure the application is running consistently across different browsers. We recommend you adopt this tool in regular practice to ease test execution.

We’ve split up this Selenium Grid tutorial into three parts. Each part has multiple steps so the code should remain easy to grasp.

1- Writing Selenium Grid Webdriver Code using TestNG in Java.

Step-1:

We will develop a test using TestNG. In the following example, we will launch the browsers on nodes using a remote web driver. It can pass on its capabilities to the driver so that the driver has all the information to execute on Nodes.

The code below will read the browser parameter from the <TestNG.xml> file.

Step-1.1: Here is the sample Selenium Grid Webdriver code to run parallel tests.

package seleniumGrid;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestGridClass {
	public WebDriver driver;
	public String URL, Node;
	protected ThreadLocal<RemoteWebDriver> threadDriver = null;

	@Parameters("browser")
	@BeforeTest
	public void launchbrowser(String browser) throws MalformedURLException {
		String URL = "http://www.calculator.net";

		if (browser.equalsIgnoreCase("firefox")) {
			System.out.println(" Executing on FireFox");
			String Node = "http://192.168.1.3:5566/wd/hub";
			DesiredCapabilities cap = DesiredCapabilities.firefox();
			cap.setBrowserName("firefox");

			driver = new RemoteWebDriver(new URL(Node), cap);
			// Puts an Implicit wait, Will wait for 10 seconds before throwing
			// exception
			driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

			// Launch website
			driver.navigate().to(URL);
			driver.manage().window().maximize();
		} else if (browser.equalsIgnoreCase("chrome")) {
			System.out.println(" Executing on CHROME");
			DesiredCapabilities cap = DesiredCapabilities.chrome();
			cap.setBrowserName("chrome");
			String Node = "http://192.168.1.3:5567/wd/hub";
			driver = new RemoteWebDriver(new URL(Node), cap);
			driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

			// Launch website
			driver.navigate().to(URL);
			driver.manage().window().maximize();
		} else if (browser.equalsIgnoreCase("ie")) {
			System.out.println(" Executing on IE");
			DesiredCapabilities cap = DesiredCapabilities.chrome();
			cap.setBrowserName("ie");
			String Node = "http://192.168.1.3:5568/wd/hub";
			driver = new RemoteWebDriver(new URL(Node), cap);
			driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

			// Launch website
			driver.navigate().to(URL);
			driver.manage().window().maximize();
		} else {
			throw new IllegalArgumentException("The Browser Type is Undefined");
		}
	}

	@Test
	public void calculatepercent() {
		// Click on Math Calculators
		driver.findElement(By.xpath("//a[contains(text(),'Math')]")).click();
		// Click on Percent Calculators
		driver.findElement(
				By.xpath("//a[contains(text(),'Percentage Calculator')]"))
				.click();
		// Enter value 17 in the first number of the percent Calculator
		driver.findElement(By.id("cpar1")).sendKeys("17");
		// Enter value 35 in the second number of the percent Calculator
		driver.findElement(By.id("cpar2")).sendKeys("35");

		// Click Calculate Button
		driver.findElement(
				By.xpath("(//input[contains(@value,'Calculate')])[1]")).click();
		// Get the Result Text based on its xpath
		String result = driver.findElement(
				By.xpath(".//*[@id='content']/p[2]/font/b")).getText();
		// Print a Log In message to the screen
		System.out.println(" The Result is " + result);
		if (result.equals("5.95")) {
			System.out.println(" The Result is Pass");
		} else {
			System.out.println(" The Result is Fail");
		}
	}

	@AfterTest
	public void closeBrowser() {
		// driver.quit();
	}
}

Step-2:

So, you just need to copy-paste the above into a Java file in the Eclipse IDE. In the next few steps, we’ll tell you how to add the <TestNG.xml> to your code and what to keep in this file.

We use this file to pass the browser parameter and to specify the test order. So, first of all, create an XML under the project folder in the Eclipse IDE.

create an XML
Selenium Grid Webdriver Code – 1.2

Step-3:

Select the <File> option from the <General> menu and press the <Next> button.

Selenium Grid Webdriver Code - 1.3
Selenium Grid Webdriver Code – 1.3

Step-4:

Enter the name of the file as <GridDemo.xml> and press the <Finish> button. By default, its name is <TestNG.xml>.

Name the file as GridDemo.xml
Selenium Grid Webdriver Code – 1.4

Step-5:

You can now see that file <GridDemo.xml> gets created under the project folder as shown below.

Selenium Grid Webdriver Code - 1.5
Selenium Grid Webdriver Code – 1.5

Step-6:

In this section, you can view the contents of the XML file. Please check that we’ve added three tests and put them in a suite. Also, we mentioned <parallel=”tests”>. So, all the tests could run in parallel.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests">

   <test name="FirefoxTest">
   <parameter name="browser" value="firefox" />
      <classes>
         <class name="seleniumGrid.TestGridClass" />
      </classes>
   </test>

   <test name="ChromeTest">
   <parameter name="browser" value="chrome" />
      <classes>
         <class name="seleniumGrid.TestGridClass" />
      </classes>
   </test>

   <test name="IETest">
   <parameter name="browser" value="ie" />
      <classes>
         <class name="seleniumGrid.TestGridClass" />
      </classes>
   </test>
   
</suite>

You’ve now completed the development part of the Selenium Grid Webdriver code. So, what remains is the execution of the tests on multiple browsers. Check out the second part to see the test execution.

2- Test Execution.

Step-1:

Select the created XML i.e. <GridDemo.xml>. Right-click and choose the <Run As >> TestNG Suite> option.

choose the Run As >> TestNG Suite> option.
Selenium Grid Webdriver Code – 2.1

Step-2:

Now open the Node where we have launched all the browsers. You will see all of them running simultaneously.

Note: For setting up the hub node, please check our earlier post on download and use Selenium Grid to run multiple browsers.

Selenium Grid Webdriver Code - 2.2
Selenium Grid Webdriver Code – 2.2

3- Result Analysis.

Step-1:

After successfully completing the test execution, the result summary gets printed in the console as you can view from the below snapshot.

Test execution, the result summary
Selenium Grid Webdriver Code – 3.1

Step-2:

Next, to see the status of all tests, Navigate to the <Results of Running Suite> Tab. Here, TestNG displays the result summary in the following manner.

Selenium Grid Webdriver Code - 3.2
Navigate to the Test Results

Step-3:

Finally, let’s check out the auto-generated <TestNG> report. With this, we’ll be able to see the test results in HTML format.

Auto-generated TestNG report
TestNG Report

Footnote – Selenium Grid Webdriver Code Example

We hope the above tutorial will help you in using Selenium Grid in your environment. And you’ll be able to speed up the test execution by running tests in parallel using Selenium Grid. Also, if you decide to use Selenium for load testing, then please share your experience after you implement it.

Hope, you succeed in reaping the full benefits from reading our latest post on the Selenium Webdriver and Selenium Grid.

Thanks to you all for visiting. Please drop your feedback in the comment box section.

All the Best,

TechBeamers.

You Might Also Like

20 Demo Sites for Automation Testing

Page Object Model (POM) and Page Factory Guide in Selenium Java

Selenium 4 Relative Locators Guide

Selenium Version 4 Features – What’s New?

How to Inspect Element in Safari, Android, and iPhone

TAGGED:Webdriver Exercises
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Selenium Webdriver Cucumber Interview Questions How to: Selenium Webdriver Cucumber Interview
Next Article Software Automation Testing Quiz for Dummies Software Automation Testing Quiz for Dummies

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x