Selenium Grid | RemoteWebDriver and DesiredCapabilities
Learn how to write code to utilise Selenium Grid setup and run the test on a node using RemoteWebDriver and DesiredCapabilities.
In the Previous Tutorial, you learned how to implement the Selenium Grid architecture. In this tutorial, I'll write code to utilise that setup and run the test on a node.
Cheers, only the code to specify browser name, version, Platform and other environment details is different. Once you have launched browser rest all code are same as normal WebDriver code.
The DesiredCapabilties object specifies the desired environment capabilities that we want for the test. For instance, let us say we want to run our test on a Windows machine against Google Chrome browser:
You need to import this package at the top of the file:
import org.openqa.selenium.remote.DesiredCapabilities;
Next, instantiate DesiredCapabilities and specify all capabilities that we want for the test:
DesiredCapabilities caps = DesiredCapabilities.chrome();
caps.setPlatform(Platform.WINDOWS);
caps.setVersion("60");
We need to tell WebDriver client the URL of the hub so that it can send the test commands to that server. The hub will further route it to one of the registered nodes with the matching capabilities as we specified above. As you remember in the Previous Tutorial, we started a Hub in the local machine.
Let us now write code to launch the browser. For that, we need to instantiate RemoteWebDriver and pass it the URL of the hub and the DesiredCapabilities object.
//Create a URL. We need to handle MalformedURLException
URL urlHub = new URL("http://127.0.0.1:4444/wd/hub");
WebDriver driver = new RemoteWebDriver(urlHub, caps);
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("teachmeselenium");
driver.quit();
Full Example
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class SeleniumGridPractice {
public static void main(String[] args) {
//Set your browser driver path
DesiredCapabilities caps = DesiredCapabilities.chrome();
//caps.setVersion("20");
caps.setPlatform(Platform.WINDOWS);
URL urlHub = null;
try {
urlHub = new URL("http://127.0.0.1:4444/wd/hub");
} catch (MalformedURLException e) {
e.printStackTrace();
}
WebDriver driver = new RemoteWebDriver(urlHub, caps);
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("teachmeselenium");
driver.quit();
}
}
Please update the DesiredCapabilities object in the code as per the platform, browser and browser version of the node.
That is Ok but isn't the whole grid-node setup is so confusing and a lot of work.
That is why we have some providers that provide ready-to-use infrastructure over the cloud. We'll cover it in the Next Tutorial.