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.
- 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.
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.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.
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.
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.
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.
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.
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.
- 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.
- "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."