RemoteWebDriver usage in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.net.URL; import java.time.Duration; public class RemoteWebDriverLoginTest { public static void main(String[] args) { WebDriver driver = null; try { // Set desired capabilities for browser (Chrome example) DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setBrowserName("chrome"); // Connect to Selenium Grid hub driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities); // Navigate to login page driver.get("https://example.com/login"); // Enter username WebElement usernameInput = driver.findElement(By.id("username")); usernameInput.sendKeys("testuser"); // Enter password WebElement passwordInput = driver.findElement(By.id("password")); passwordInput.sendKeys("Test@123"); // Click login button WebElement loginButton = driver.findElement(By.id("loginBtn")); loginButton.click(); // Wait for URL to change to dashboard WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.urlToBe("https://example.com/dashboard")); // Verify welcome message WebElement welcomeMessage = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("welcomeMessage"))); String messageText = welcomeMessage.getText(); if ("Welcome, testuser!".equals(messageText)) { System.out.println("Test Passed: Welcome message is correct."); } else { System.out.println("Test Failed: Welcome message is incorrect."); } } catch (Exception e) { System.out.println("Test Failed due to exception: " + e.getMessage()); } finally { if (driver != null) { driver.quit(); } } } }
This test script uses RemoteWebDriver to connect to a Selenium Grid hub running at http://localhost:4444/wd/hub. We set the desired browser capabilities to Chrome.
The script navigates to the login page, enters the username and password using By.id locators, and clicks the login button.
We use an explicit wait (WebDriverWait) to wait until the URL changes to the dashboard page, ensuring the login was successful.
Then, we wait for the welcome message element to be visible and verify its text matches the expected greeting.
The test prints a pass or fail message based on the assertion and always closes the browser session in the finally block to clean up resources.
Now add data-driven testing with 3 different username and password combinations to verify login functionality.