UI Automation Interview Questions and Answers
20 hand-picked UI Automation interview questions with
detailed answers. Open the interactive version above to search, filter
by difficulty, run code, bookmark questions and track your progress.
What is Selenium WebDriver? How does it work at a high level?
Selenium WebDriver is a tool/API for automating browsers. Your test code (e.g. Java) sends commands to a browser driver (ChromeDriver, GeckoDriver), which controls the real browser to click, type, navigate, and assert UI behaviour.
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/login");
driver.findElement(By.id("email")).sendKeys("a@b.com");
driver.findElement(By.id("password")).sendKeys("secret");
driver.findElement(By.id("loginBtn")).click();
What are Selenium locators? Which ones do you prefer and why?
Locators tell WebDriver how to find an element: id, name, cssSelector, xpath, linkText, etc.
Prefer stable attributes: id or dedicated test ids (data-testid). Avoid long absolute XPaths tied to layout — they break when UI changes.
By.id("loginBtn")
By.cssSelector("[data-testid='submit-order']")
By.xpath("//button[normalize-space()='Place Order']")
Implicit wait vs Explicit wait vs Thread.sleep — which should you use?
Thread.sleep always waits a fixed time — slow and flaky; avoid in real suites.
Implicit wait sets a global timeout for findElement polling — easy but blunt; can hide issues and slow failures.
Explicit wait (WebDriverWait + expected conditions) waits for a specific condition (visible, clickable, text present) — preferred for reliable UI tests.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement btn = wait.until(
ExpectedConditions.elementToBeClickable(By.id("placeOrder"))
);
btn.click();
What is the Page Object Model (POM)? Why use it?
Page Object Model is a design pattern where each page/component has a class that stores its locators and user actions (login, search, add to cart). Tests call those methods instead of raw Selenium calls.
Benefits: less duplication, easier maintenance when UI changes, and more readable tests.
public class LoginPage {
private By email = By.id("email");
private By password = By.id("password");
private By loginBtn = By.id("loginBtn");
private WebDriver driver;
public LoginPage(WebDriver driver) { this.driver = driver; }
public HomePage login(String user, String pass) {
driver.findElement(email).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
return new HomePage(driver);
}
}
What is TestNG and how do you use it with Selenium?
TestNG is a Java testing framework used to organise and run automated tests. With Selenium you write test methods annotated with @Test, use annotations like @BeforeMethod/@AfterMethod for setup/teardown, and configure suites via testng.xml.
It supports assertions, groups, dependencies, data providers, and parallel execution — commonly run through Maven.
public class LoginTest {
WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
}
@Test
public void validLogin_showsHomePage() {
new LoginPage(driver).login("a@b.com", "secret");
Assert.assertTrue(new HomePage(driver).isLoaded());
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
Why do UI automated tests become flaky, and how do you reduce flakiness?
Flaky tests pass/fail without code changes. Common causes: timing races, unstable locators, shared test data, environment issues, animations, and order-dependent tests.
Reduce flakiness with explicit waits, stable locators, isolated data, idempotent setup/cleanup, avoiding sleeps, and quarantining/fixing flakes instead of re-running until green.
findElement vs findElements in Selenium?
findElement returns the first matching element or throws NoSuchElementException if none. findElements returns a list (empty if none) — useful to check presence without try/catch.
List<WebElement> errors = driver.findElements(By.cssSelector(".error"));
if (!errors.isEmpty()) { /* assert message */ }
How do you handle alerts, frames, and multiple windows in Selenium?
- Alerts:
driver.switchTo().alert() then accept/dismiss/getText/sendKeys. - Frames: switch by index/name/WebElement, then switch back to default content.
- Windows: store parent handle, switch to new handle from
getWindowHandles().
String parent = driver.getWindowHandle();
for (String h : driver.getWindowHandles()) {
if (!h.equals(parent)) driver.switchTo().window(h);
}
When do you use the Actions class in Selenium?
Use Actions for complex user gestures: hover, double-click, right-click, drag-and-drop, key chords. Ordinary click/sendKeys cover most flows; Actions is for advanced interactions.
Actions a = new Actions(driver);
a.moveToElement(menu).perform();
a.dragAndDrop(source, target).perform();
How do you handle dropdowns in Selenium?
For HTML <select>, use Selenium’s Select helper (by visible text/value/index). For custom dropdowns (divs), click the control, wait for options, then click the option element.
Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("India");
What is StaleElementReferenceException and how do you fix it?
It means the element you found is no longer attached to the DOM (page refreshed/re-rendered). Fix by re-finding the element after the update, using waits for the new DOM state, and avoiding long-lived WebElement references across navigations.
wait.until(ExpectedConditions.refreshed(
ExpectedConditions.elementToBeClickable(By.id("save"))
)).click();
How and when do you capture screenshots in UI automation?
Capture on failure (and optionally on key checkpoints) using TakesScreenshot, save with test name + timestamp, and attach to reports/CI artifacts. Screenshots make Jenkins failures diagnosable.
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshots/" + testName + ".png"));
How do you do data-driven testing with TestNG DataProvider?
A @DataProvider supplies rows of input data to a @Test method so the same flow runs with multiple datasets (valid login, invalid password, locked user). Data can be hardcoded or read from Excel/CSV/JSON.
@DataProvider(name="loginData")
public Object[][] loginData() {
return new Object[][] {
{"valid@test.com", "Valid@123", true},
{"valid@test.com", "wrong", false}
};
}
@Test(dataProvider="loginData")
public void login(String user, String pass, boolean ok) { /* ... */ }
How do you run Selenium tests in parallel safely?
Enable TestNG parallel methods/classes and isolate WebDriver per thread (often with ThreadLocal<WebDriver>). Tests must not share mutable state/users. Use Selenium Grid/cloud for multiple browsers/nodes.
parallel="methods" thread-count="4"
What is Selenium Grid? When do you use it?
Selenium Grid runs tests on remote machines/browsers via RemoteWebDriver. Use it for cross-browser coverage and scale (many nodes) in CI instead of only local Chrome.
WebDriver driver = new RemoteWebDriver(gridUrl, chromeOptions);
How does Maven fit into a Selenium + TestNG framework?
Maven manages dependencies (Selenium, TestNG, WebDriverManager) and runs tests via Surefire/Failsafe, often pointing at a testng.xml. The same mvn test command runs locally and in Jenkins.
mvn clean test -DsuiteXmlFile=smoke.xml
How do you manage browser drivers (ChromeDriver) today?
Use Selenium Manager (Selenium 4.6+) or WebDriverManager to resolve matching drivers automatically instead of manually downloading ChromeDriver binaries. Manual driver paths break often after browser updates.
// Selenium 4.6+ often needs no manual driver setup
WebDriver driver = new ChromeDriver();
Hard assert vs soft assert in TestNG?
Hard assert fails the test immediately on mismatch. Soft assert collects failures and continues, then reports all at assertAll() — useful when checking multiple independent fields on one page.
SoftAssert soft = new SoftAssert();
soft.assertEquals(title, "Order Details");
soft.assertTrue(status.contains("CREATED"));
soft.assertAll();
How would you structure a maintainable Selenium framework?
Typical layers: tests (TestNG scenarios), pages (POM), components/services (reusable flows), utilities (waits, screenshots, config), testdata, and driver factory. Keep business-readable tests and push Selenium details downward.
tests/ → pages/ → utils/driver/ → testdata/
What should you automate in UI vs leave manual?
Automate stable, high-value, repetitive paths (smoke, regression critical journeys). Leave exploratory, frequently changing UX experiments, and one-off edge visuals more manual. If a check is cheaper/faster at API level, prefer API automation.