Skip to content
VirtualLP Virtual Learning Platform

Practical 16: Web Testing using WebDriver

16 min read Topic 25 of 31 1 hands-on lab

Aim

Set up Selenium WebDriver in Java. Automate the checkout steps. Wait for page elements to become ready, check the order result and capture screenshots.

Theory

Selenium WebDriver lets a program control a browser. It can open pages, enter text, click buttons and read page contents.

A browser driver, such as ChromeDriver or GeckoDriver, connects the test commands to the browser. Some page elements appear later, so the test must wait for them before acting.

online shopping by a robot

The test is a robot shopper: it opens a product, clicks Add to cart, goes to the cart, fills the address and places the order – exactly like you would. Waits are the robot's patience: it waits until the cart number actually changes before moving on, instead of rushing ahead. Screenshots are the photos it takes at each step as proof.

flowchart LR
    T[Test code<br/>Java bindings] -- W3C WebDriver protocol<br/>HTTP + JSON --> D[Browser driver<br/>chromedriver] -- native automation --> B[Chrome] --> A[Web application]

Since Selenium 4.6, Selenium Manager downloads the correct driver automatically.

Core API

API means Application Programming Interface.

Item Example
Open browser WebDriver driver = new ChromeDriver();
Navigate driver.get(url), navigate().back()
Find element(s) driver.findElement(By.id("x")), findElements(By.cssSelector(".item"))
Interact click(), sendKeys("text"), clear(), submit()
Read getText(), getAttribute("value"), isDisplayed(), isEnabled()
Drop-down new Select(element).selectByVisibleText("India")
Windows / frames / alerts switchTo().window(h), switchTo().frame("f"), switchTo().alert().accept()
Actions new Actions(driver).moveToElement(e).click().perform()
JavaScript ((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)")
Screenshot ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE)
Close driver.close() (window) / driver.quit() (session)

Synchronisation techniques

Some page contents appear after the page first opens. Wait for the required element before using it. Otherwise, the test may report NoSuchElementException or ElementNotInteractableException even when the feature works.

Technique How When
Implicit wait driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)) – every findElement polls up to the timeout Global default; simple pages
Explicit wait new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(by)) Wait for a specific condition – recommended
Fluent wait new FluentWait<>(driver).withTimeout(…).pollingEvery(…).ignoring(NoSuchElementException.class) Custom polling interval and ignored exceptions
Thread.sleep() Fixed pause Avoid – slow and flaky

Useful ExpectedConditions: visibilityOfElementLocated, elementToBeClickable, textToBePresentInElementLocated, invisibilityOfElementLocated (spinners), urlContains, alertIsPresent, numberOfElementsToBe.

Don’t mix implicit and explicit waits

Mixing them can produce unpredictable wait times. Prefer explicit waits for dynamic elements.

Requirements

The .test addresses refer to the simulated practice app. Outside the simulator, use a running test app and its actual addresses and page elements.

  • Eclipse, JDK (Java Development Kit) 17, Selenium Java 4.21+, JUnit 4 or TestNG (Test Next Generation), Chrome.
  • AUT (Application Under Test): VLP Demo Store checkout flow: product page → Add to cart (AJAX (Asynchronous JavaScript and XML), cart badge updates after a delay) → cart → Checkout → shipping form → payment method → Place order (spinner for 2–3 s) → order confirmation with an order number.

Procedure

  1. Create a Java project WebDriverCheckout, add Selenium and JUnit to the build path (as in Practical 15).
  2. Create folder screenshots in the project.
  3. Write the test below.
  4. Run As → JUnit Test; observe Chrome performing the purchase.
  5. Open the screenshots folder to review one image per step.

Program – CheckoutTest.java

package vlp.webdriver;

import static org.junit.Assert.*;
import java.io.File;
import java.nio.file.*;
import java.time.Duration;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.*;

public class CheckoutTest {

    private WebDriver driver;
    private WebDriverWait wait;
    private int step = 0;

    @Before
    public void setUp() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, Duration.ofSeconds(15));      // explicit wait
        driver.get("https://demo.virtuallp.test/login");
        driver.findElement(By.id("username")).sendKeys("student");
        driver.findElement(By.id("password")).sendKeys("Pass@123");
        driver.findElement(By.cssSelector("button[type=submit]")).click();
        wait.until(ExpectedConditions.urlContains("/dashboard"));
    }

    @Test
    public void completeCheckout() throws Exception {
        // 1. Search and open a product
        driver.findElement(By.id("search")).sendKeys("wireless mouse" + Keys.ENTER);
        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".product-card a"))).click();
        screenshot("product-page");

        // 2. Add to cart – the badge updates asynchronously
        driver.findElement(By.id("add-to-cart")).click();
        wait.until(ExpectedConditions.textToBePresentInElementLocated(By.id("cart-count"), "1"));
        screenshot("added-to-cart");

        // 3. Go to cart and verify the line item
        driver.findElement(By.id("cart-link")).click();
        WebElement item = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".cart-item .name")));
        assertEquals("Wireless Mouse", item.getText());
        screenshot("cart");

        // 4. Checkout – fill shipping details
        driver.findElement(By.id("checkout")).click();
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("address")));
        driver.findElement(By.id("fullName")).sendKeys("Priya Sharma");
        driver.findElement(By.id("address")).sendKeys("12, Marine Drive");
        driver.findElement(By.id("city")).sendKeys("Mumbai");
        driver.findElement(By.id("pincode")).sendKeys("400020");
        new Select(driver.findElement(By.id("state"))).selectByVisibleText("Maharashtra");
        screenshot("shipping");

        // 5. Payment method and place order
        driver.findElement(By.cssSelector("input[value='cod']")).click();
        driver.findElement(By.id("place-order")).click();

        // Fluent wait: spinner disappears, then confirmation appears
        Wait<WebDriver> fluent = new FluentWait<WebDriver>(driver)
                .withTimeout(Duration.ofSeconds(20))
                .pollingEvery(Duration.ofMillis(500))
                .ignoring(NoSuchElementException.class);
        fluent.until(ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".spinner")));
        WebElement confirmation = fluent.until(d -> d.findElement(By.cssSelector(".order-success")));

        // 6. Verify
        assertTrue(confirmation.getText().contains("Thank you for your order"));
        String orderId = driver.findElement(By.id("order-number")).getText();
        assertTrue("Order number format", orderId.matches("VLP-\\d{6}"));
        screenshot("order-confirmation");
        System.out.println("Order placed successfully: " + orderId);
    }

    private void screenshot(String name) throws Exception {
        File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        Path dest = Paths.get("screenshots", String.format("%02d-%s.png", ++step, name));
        Files.createDirectories(dest.getParent());
        Files.copy(src.toPath(), dest, StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Saved " + dest);
    }

    @After
    public void tearDown() {
        if (driver != null) driver.quit();
    }
}

Virtual lab · Testing Tools · 35 min

Automate a complete checkout with Selenium WebDriver

Run an end-to-end purchase test on the VLP Demo Store, discover why a fixed Thread.sleep makes it fail, replace it with an explicit wait, and review the screenshots captured at every step.

Open lab

Output

Example output for the settings in this lesson:

Saved screenshots\01-product-page.png
Saved screenshots\02-added-to-cart.png
Saved screenshots\03-cart.png
Saved screenshots\04-shipping.png
Saved screenshots\05-order-confirmation.png
Order placed successfully: VLP-482913

JUnit: Runs: 1/1  Errors: 0  Failures: 0

Observations

  • Without the explicit wait on #cart-count, the test intermittently failed because the cart badge updates ~1 s after the click.
  • The fluent wait ignored NoSuchElementException while polling every 500 ms for the confirmation after the spinner vanished.
  • Screenshots provide evidence for each step and help debug failures.

Conclusion

Check that the script completes checkout and checks the order. Confirm that waits handle elements that appear after a delay. Save screenshots that show the main steps and the final result.

Viva questions

  1. Explain the WebDriver architecture. Test code (language binding) → W3C (World Wide Web Consortium) WebDriver commands over HTTP (Hypertext Transfer Protocol) → browser driver (ChromeDriver…) → browser.
  2. Differentiate driver.close() and driver.quit(). close() closes the current window; quit() closes all windows and ends the driver session.
  3. What are implicit, explicit and fluent waits? Which is recommended? Implicit = global wait when finding elements; explicit = wait for a specific condition; fluent = explicit with custom polling and ignored exceptions. Explicit is recommended.
  4. Name five ExpectedConditions. visibilityOfElementLocated, elementToBeClickable, presenceOfElementLocated, textToBePresentInElement, invisibilityOfElementLocated (also titleContains, alertIsPresent).
  5. How do you capture a screenshot in WebDriver? ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE) and copy the file.
  6. How do you select a value from a drop-down? new Select(element).selectByVisibleText("…") (or selectByValue / selectByIndex).
  7. Why should Thread.sleep() be avoided? It always waits the full time – slow when the page is fast and still fails when it is slower.
  8. What is Selenium Manager? The built-in tool (Selenium 4.6+) that finds or downloads the right browser driver automatically.

Practise this topic

Hands-on virtual lab

Apply what you just read in a realistic, guided simulation. Free with a verified account.

Create a free account to track your progress and unlock virtual labs.