Close Menu
TechBeamersTechBeamers
    TechBeamersTechBeamers
    • Python
    • Java
    • C
    • SQL
    • MySQL
    • Selenium
    • Testing
    • Agile
    • Linux
    • WebDev
    • Technology
    TechBeamersTechBeamers
    Selenium Tutorial

    Selenium Grid Webdriver Code Example

    By Meenakshi AgarwalUpdated:Sep 29, 2023No Comments7 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    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.

    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.

    See also  TestNG Interview Questions for Sure Success in 2023

    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.

    See also  A 10 Min Guide: Download and Set up Selenium Grid

    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.

    See also  3 Unique Ways to Generate Reports in Selenium

    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.

    Advanced Selenium Tutorial Selenium for Load Testing Webdriver Exercises
    Previous ArticleHow to: Selenium Webdriver Cucumber Interview
    Next Article Understand Webdriver Fluent Wait with Examples
    Meenakshi Agarwal

    I'm Meenakshi Agarwal, founder of TechBeamers.com, with 10+ years of experience in Software development, testing, and automation. Proficient in Python, Java, Selenium, SQL, & C-Sharp, I create tutorials, quizzes, exercises and interview questions on diverse tech topics. Follow my tutorials for valuable insights!

    Add A Comment

    Leave A Reply Cancel Reply

    Top Selenium Questions
    • Selenium Interview Q&A
    • Selenium Webdriver Q&A
    • Selenium Testing Q&A
    • Common Selenium Q&A
    • Selenium Coding Q&A
    • Selenium Java Q&A
    • Selenium Appium Q&A
    • Selenium Cucumber Q&A
    • TestNG Interview Q&A
    Top Selenium Quizzes
    • Selenium Quiz-1
    • Selenium Quiz-2
    • Selenium Quiz-3
    • Selenium Python Quiz
    • Selenium Appium Quiz
    • Selenium TestNG Quiz-1
    • Selenium TestNG Quiz-2
    Top Selenium Tutorials
    • Selenium WebDriver Download & Install
    • Selenium Report Generation
    • Handle File Upload
    • Handle HTML Tables
    • Handle Keyboard/Mouse
    • Handle AJAX Calls
    • Handle Date-Time Picker
    • Run Selenium Tests Using Task Schedular
    • Selenium to Add Items to a Cart
    Selenium Grid Tutorial
    • Selenium Grid Download
    • Setup Selenium Grid
    Top Selenium Tips
    • Selenium HowTos
    • Selenium Coding Tips
    • Essential Selenium Skills
    • Sample Selenium Resume
    • Selenium Job Profile Tips
    TestNG Tutorials
    • Install TestNG In Eclipse
    • TestNG Annotations
    • TestNG Assertions
    • TestNG Parameters
    • TestNG DataProvider
    • Create TestNG Tests
    • TestNG Using Maven
    • TestNG Result in Excel
    • TestNG Threads - Demo
    • TestNG Factory - Demo
    • Write Data Driven Tests
    Selenium IDE
    • Selenium IDE Download
    • Use Selenium IDE
    • Selenium IDE Add-ons
    Selenium Locators
    • How to Use Locators
    • FireBug & FirePath
    • XPath Chrome Extensions
    • Locator Best Practices
    • Locator Strategies
    Selenium Web Elements
    • Find Web Elements
    • Dropdown & Multi Selects
    • Checkbox & Radio Buttons
    Create Selenium Projects
    • Setup Selenium2 Project
    • Setup Selenium3 Project
    • Use Selenium Maven
    • Selenium Maven Project
    • How to Use IE Driver
    • How to Use Chrome Driver
    Selenium Framework- Java
    • Data Driven Framework
    • Page Object Model (POM)
    • Object Repository (OR)
    • POM vs OR
    Latest Posts
    • 10 Selenium Technical Interview Questions and Answers.
    • 100+ Selenium Interview Questions and Answers You Need to Know in 2024
    • 15 Java Coding Questions for Testers
    • 20 Most Unique Appium Questions and Answers
    • 3 Unique Ways to Generate Reports in Selenium
    • 3 Unique Ways to Handle File Upload In Selenium
    • 35 Selenium Webdriver Questions for Interview

    Subscribe to Updates

    Get the latest tutorials from TechBeamers.

    Loading
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    © 2023 TechBeamers. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.