QA AND TEST AUTOMATION · PART 5 · UI WEB AUTOMATION · SELENIUM · 52 OF 112

Selenium 4 With Java: WebDriver Tutorial

Selenium WebDriver 4 in Java with JUnit 5, written for ShopRung: how WebDriver works, Selenium Manager for drivers, starting Chrome headless, By locators, findElement versus findElements, explicit waits, a login and add-to-cart test, Actions, JavaScript and screenshots, relative locators, and what WebDriver BiDi adds. The same flow in Python is included.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • WebDriver protocol
  • Selenium Manager
  • driver per test, quit
  • By locators
  • wait then assert
  • Actions, JS, screenshots

Notes

How it works

Here is how Selenium works. Your Java code calls the Selenium client library. The library sends commands, like find element or click, using the W3C WebDriver protocol, which is an official web standard, to a driver program such as chromedriver for Chrome or geckodriver for Firefox. The driver controls the real browser. Since Selenium four point six, Selenium Manager finds or downloads a matching driver automatically, so the old driver setup pain is mostly gone.

The chain
  • your Java code calls the Selenium client library
  • it sends W3C WebDriver HTTP commands ("find element", "click") to a driver
  • chromedriver / geckodriver controls the real browser
  • Selenium Manager (4.6+) finds or downloads the right driver

Setup

Add the selenium java dependency to the Maven project. Before each test, create Chrome options, add headless new so no window opens in CI, start a Chrome driver, create a web driver wait with a ten second timeout, and reset ShopRung through its API. After each test, call quit, never just close: quit ends the browser and the driver process, otherwise CI machines fill up with orphaned browsers.

Start and stop
WebDriver driver;
WebDriverWait wait;
@BeforeEach void start() {
  var o = new ChromeOptions();
  o.addArguments("--headless=new");
  driver = new ChromeDriver(o);
  wait = new WebDriverWait(driver,
    Duration.ofSeconds(10));
  resetShopRungViaApi();
}
@AfterEach void stop() { driver.quit(); }

Locators

Selenium locates elements with the By class: by id, by name, by CSS selector, by XPath and by link text. There is no built in role locator, so CSS on data test ids and stable attributes is the common choice. Find element returns one element, the first match, or throws no such element exception. Find elements returns a list, which may be empty, and never throws, which makes it the right way to check that something is absent.

By strategies
By.id("q")
By.name("email")
By.cssSelector(
  "[data-testid=cart-count]")
By.xpath("//button[.='Log in']")
By.linkText("Orders")

findElement → one, or
  NoSuchElementException
findElements → list (maybe
  empty), never throws

The test

The test. Get the login page. ShopRung renders it with JavaScript, so wait until the email field is visible, then type Alice's email. Type the password, and click the button whose text is log in. Wait until the user name in the header is visible, proving login finished. Then click the add button for the clean code notebook, found by CSS on its aria label, and wait for the cart count's text to become one.

AddToCartTest
driver.get(BASE + "/#/login");
wait.until(visibilityOfElementLocated(
    By.name("email")))
  .sendKeys("alice@shoprung.test");
driver.findElement(By.name(
  "password")).sendKeys(PW);
driver.findElement(By.xpath(
  "//button[.='Log in']")).click();
wait.until(visibilityOfElementLocated(
    USER_NAME));
driver.findElement(ADD_NOTEBOOK)...

Assert after waiting

Selenium does not have retrying assertions, so the pattern is: wait for the state, then assert. Wait until the cart count's text is one, then assert equals one with JUnit, which documents the expectation and gives a clear message. To check something is absent, use find elements and assert the list is empty. Keep locators as named constants, or better, in page objects, which is two episodes away.

Checking the result
By COUNT = By.cssSelector(
  "[data-testid=cart-count]");
wait.until(textToBe(COUNT, "1"));
assertEquals("1",
  driver.findElement(COUNT)
        .getText());

absent check:
assertTrue(driver.findElements(
  By.cssSelector(".error"))
  .isEmpty());

Beyond clicks

Beyond simple clicks. The Actions class builds hover, drag and drop, keyboard combinations and double clicks, then performs them. The JavaScript executor runs scripts in the page; use it sparingly, because it bypasses what a real user can do. Takes screenshot saves a picture, ideally automatically when a test fails. And the select helper handles native drop downs, like ShopRung's category filter, by visible text.

Useful APIs
new Actions(driver)
  .moveToElement(menu)
  .keyDown(Keys.SHIFT).click(x)
  .perform();
((JavascriptExecutor) driver)
  .executeScript("window.
    scrollTo(0, 0)");
File f = ((TakesScreenshot)
  driver).getScreenshotAs(
  OutputType.FILE);
new Select(el).selectByVisibleText

New in Selenium 4

Selenium four added useful features. Relative locators find elements by position, like the input below the search box, handy but fragile. Switch to new window opens a tab directly. Get shadow root reaches inside web components. WebDriver BiDi, a newer two way standard, lets tests listen for console logs and network events across browsers, replacing older Chrome only tricks. And Selenium Grid four, covered later in this part, runs tests across many machines.

Selenium 4 additions
RelativeLocator.with(
  By.tagName("input"))
  .below(By.id("q"))
driver.switchTo()
  .newWindow(WindowType.TAB)
element.getShadowRoot()
WebDriver BiDi: two-way events
  (console logs, network)
  replacing Chrome-only CDP
Grid 4: Docker, distributed

Python too

Python's Selenium package mirrors the Java API with snake case names. Get the page, wait with expected conditions for the email field, send keys, find the password field by name, click, and wait for the cart count text. Driver setup goes in a pytest fixture that yields the driver and quits it afterwards, like the API client fixture from Part four.

selenium (Python)
from selenium.webdriver.support import (
    expected_conditions as EC)
d.get(BASE + "/#/login")
w.until(EC.visibility_of_element_located(
    (By.NAME, "email"))).send_keys(
    "alice@shoprung.test")
d.find_element(By.NAME,
    "password").send_keys(PW)
...
w.until(EC.text_to_be_present_in_element(
    COUNT, "1"))

Common mistakes

Selenium mistakes. Thread sleep instead of explicit waits. Mixing implicit and explicit waits. Close instead of quit, leaving drivers running. One shared static driver for all tests, which breaks parallel runs and leaks state. Keeping element references across re renders, which throws stale element reference exceptions; locate again instead. And using find element to check absence, which waits for the implicit timeout and then throws.

Avoid these
  • Thread.sleep instead of waits
  • implicit + explicit waits mixed
  • close() instead of quit()
  • one shared driver for all tests
  • stale element references kept across re-renders
  • findElement for absence checks (slow exceptions)

Say it like this

In the interview: the client library sends W3C WebDriver commands over HTTP to a browser specific driver, which controls the real browser, and Selenium Manager resolves the driver. I create a driver per test and quit it afterwards, use CSS or data test id locators, explicit waits for exact conditions followed by JUnit assertions, capture screenshots on failure, and scale out with Selenium Grid.

In the interview
  • "The client library sends W3C
  • WebDriver commands to a browser driver, which controls
  • the browser; Selenium Manager
  • resolves drivers. I create a driver per test, quit it after, use CSS or data-testid By locators, explicit waits, then JUnit asserts, screenshots on failure, and Grid to scale."

Interview questions

Q1How does Selenium WebDriver communicate with the browser?

The client library sends W3C WebDriver protocol commands (HTTP) to a browser driver such as chromedriver, which drives the browser; WebDriver BiDi adds a two-way channel.

Q2What is Selenium Manager?

A tool bundled with Selenium since 4.6 that automatically locates or downloads the correct browser driver (and browser if needed).

Q3What is the difference between findElement and findElements?

findElement returns the first match or throws NoSuchElementException; findElements returns a list that may be empty and never throws.

Q4What is the difference between driver.close() and driver.quit()?

close() closes the current window; quit() closes all windows and ends the driver session and process.

Q5How do you handle a StaleElementReferenceException?

Locate the element again after the page re-renders, or wait for a fresh element; do not keep references across DOM updates.

Q6What are relative locators in Selenium 4?

Locators that find elements by position relative to others: above, below, toLeftOf, toRightOf and near.

Q7How do you take a screenshot in Selenium Java?

Cast the driver to TakesScreenshot and call getScreenshotAs(OutputType.FILE or BYTES); element screenshots are also supported.

Q8How do you run Selenium headless?

Add the browser's headless argument to its options, for example ChromeOptions.addArguments("--headless=new").