You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Every Selenium, TestNG and framework question this lab answers with working code. For each one you get the short answer to give in an interview, the exact class and method that implements it, and the question number in interview-questions.pdf, which has the long explanation and an example.
How to use it: find your question, say the short answer out loud, then open the implementation and read the comments. Every class starts with the interview question, the interview answer, the concept and the recommended approach; every line is commented. Trick questions are collected in Common interview traps; common mistakes next to the better code in Avoid vs prefer.
What is the difference between close() and quit()?
🟢 ⭐
close() closes the current window only; quit() closes every window and ends the driver session. Use quit() in teardown, or browsers and driver processes leak.
What is the difference between findElement and findElements?
🟢 ⭐
findElement returns one element or throws NoSuchElementException; findElements returns a list that is empty when nothing matches. Use the list form to check that something is absent.
How do you run tests headless, and what are browser options for?
🟢
Options configure the browser before it starts: headless mode, window size, flags. Headless needs no screen, so it suits CI; set the window size explicitly so the layout matches a normal run.
Since Selenium 4.6, Selenium Manager finds or downloads the right driver binary for the installed browser, so no chromedriver.exe or WebDriverManager is needed.
DriverManager.start(): just new ChromeDriver(options); there are no driver binaries in the repo
Q4
2. Locators
#
Question
Level
Interview answer
Implementation
PDF
6
Which locator strategies are there, and which do you prefer?
🟢 ⭐
id, name, className, tagName, linkText, partialLinkText, CSS and XPath. Prefer stable, meaningful attributes (id, name, data-*), then short CSS, and XPath when you need text or to move up the tree.
How do you locate dynamic elements (values known only at run time)?
🟡 ⭐
Anchor on something stable (visible text, a label, a stable class) and build the locator from the value with String.format, instead of hard-coding generated ids.
RelativeLocator.with(By.tagName("input")).below(element): find an element by its position (above, below, toLeftOf, toRightOf, near). Layout-dependent, so a real attribute is still better when there is one.
It always waits the full time: too long when the app is fast, too short when it is slow. An explicit wait polls a condition and continues as soon as it is true.
Nowhere in the code: every action in BasePage waits explicitly · interview/synchronization/ExplicitWaitTest
Q21
12
What is an implicit wait? Can you mix it with explicit waits?
🟢 ⭐
implicitlyWait(t) makes every findElement retry for up to t; it is global and only waits for existence. Don't mix it with explicit waits: the timeouts add up. Use explicit waits only.
Presence or visibility? Which ExpectedConditions do you use?
🟡 ⭐
Presence = in the DOM; visibility = in the DOM and displayed. A hidden element is present at once. Common conditions: visibilityOf…, elementToBeClickable, invisibilityOf…, textToBe, urlContains, alertIsPresent, frameToBeAvailableAndSwitchToIt.
What is a FluentWait? How is it different from WebDriverWait?
🟡 ⭐
FluentWait lets you set the timeout, polling interval, ignored exceptions and message. WebDriverWaitis a FluentWait<WebDriver> with defaults (500 ms, ignores NotFoundException).
wait.until(driver -> …): return null/false to keep waiting, any other value to stop and use it. Add withMessage(...): a lambda has no readable name in the timeout.
All in interview/exceptions/SeleniumExceptionsTest: each test reproduces the exception on purpose, then shows the fix; the Javadoc lists cause, fix and the workaround to avoid.
#
Question
Level
Interview answer
Implementation
PDF
18
NoSuchElementException: causes and handling?
🟢 ⭐
Wrong locator, element not there yet, or in another frame/window. Fix the locator, wait, or switch frame; check absence with findElements(...).isEmpty().
noSuchElementException
Q7, Q85
19
What is StaleElementReferenceException, and how do you handle it?
🟡 ⭐
The element you hold was removed from the DOM (reload, re-render, AJAX). Find it again after the change; wait with stalenessOf(old); keep locators, not elements.
The element exists but is hidden or has no size. Wait for visibility; point the locator at the visible element. Not a JavaScript click: a user can't click a hidden element either.
elementNotInteractableException
Q24
21
ElementClickInterceptedException?
🟡 ⭐
Another element (overlay, spinner, banner) is on top. Wait for it to disappear; don't switch to a JavaScript click.
Switch in by name/id, index or WebElement (frameToBeAvailableAndSwitchToIt waits too); parentFrame() goes one level up, defaultContent() back to the page.
Selenium doesn't follow it: remember the original handle, wait for the window count to grow, take the new handle by set difference (or by title), switch, work, close(), switch back.
Read isSelected() first and click only if the state must change; a click toggles a checkbox. A selected radio button is never unselected by clicking it.
Read the headers, then each row's cells, and map them by position into column → value; then any question is plain Java. Prefer stable class names over positions when the cells have them.
When do you use JavascriptExecutor? What does it return?
🟡 ⭐
For what WebDriver can't do: page state, scrolling. arguments[0…] go in; return values come back as Long, Double, String, Boolean, WebElement, List or null.
How do you work with cookies? Can you skip the login?
🟡
driver.manage(): getCookies, getCookieNamed, addCookie, deleteCookieNamed, deleteAllCookies (open a page of the site first). Saving the session cookie and adding it to a fresh session skips the login form.
One class per page holds its locators and actions; tests only call methods and assert. When the UI changes, you fix one page class instead of many tests.
Generally no: pages return values and states, tests decide what is correct. Pages may fail fast when they cannot do their job (e.g. login rejected).
LoginPage.isDisplayed() returns a boolean · LoginPage.loginAs() throws on a rejected login
Q41
46
What is PageFactory? Is it the same as POM?
🟡 ⭐
POM is a design pattern; PageFactory is one way to create the elements (@FindBy + initElements). Each field is a lazy proxy that finds the element on every use. @CacheLookup keeps the first element and goes stale after a re-render.
What every page needs: the driver, the wait, PageFactory set-up, safe actions (click, type, read) and the app's shared widgets (spinner, toast, tables).
How do you run Selenium tests in parallel safely? Is WebDriver "thread-safe"?
🔴 ⭐
Give every thread its own browser: keep the driver in a ThreadLocal<WebDriver>, never in a static field. WebDriver itself is still not thread-safe; ThreadLocal makes sure no two threads share one.
Start a fresh browser before each test, quit it after each test (in finally), remove() the ThreadLocal slot, and quit any leftover before starting a new one.
Configuration methods don't inherit class groups; under -Dgroups=… a method without alwaysRun is left out (no browser!). alwaysRun also runs teardown after failures.
Labels on tests (groups = "smoke"), selected with -Dgroups=… or <include>/<exclude> in testng.xml. A class-level group applies to every method.
Class-level groups on every test class (e.g. {"interview", "exceptions"}) · excludedGroups in pom.xml
Q55, Q75
58
What do priority and dependsOnMethods do? What if the first test fails?
🟢 ⭐
priority sorts methods before they are scheduled (lower first); it is not a dependency, and with parallel classes there is no order between classes. dependsOnMethods runs a test only if the other passed; otherwise it is skipped, not failed.
dependsOnGroups waits for a whole group to pass; alwaysRun = true makes a dependency "soft". enabled = false switches a test off: not run, not reported.
Fails the test if it runs longer than the limit: a safety net against hangs, not a replacement for waits.
TestNgFeaturesTest.loginFinishesWithinOneMinute()
Q56, Q104
62
Hard vs soft assertions?
🟢 ⭐
A hard assert stops at the first failure; SoftAssert collects every failure and reports them together at assertAll(). Forget assertAll() and the failures are lost.
TestNgFeaturesTest.softAssertChecksTheLoginPage()
Q59, Q98
63
How do you skip a test at run time?
🟢
Throw SkipException with the reason; the test is reported as skipped, with that message.
ReportDemoTest.skippedWhenPreconditionIsMissing()
Q60, Q73
64
How do you test that an exception is thrown?
🟡
@Test(expectedExceptions = X.class, expectedExceptionsMessageRegExp = "…"), or inside a test assertThrows / expectThrows (which returns the exception to inspect).
10. TestNG data, parallel runs, listeners and retry
#
Question
Level
Interview answer
Implementation
PDF
65
How does a @DataProvider work? How do you share one?
🟡 ⭐
It returns Object[][]; TestNG runs the test once per row with the row as parameters. Share it by putting it in another class and naming it with dataProviderClass.
A lazy Iterator<Object[]>; a provider with a Method parameter that serves several tests; parallel = true to run rows at the same time (the test must then be thread-safe).
@Parameters passes single values from testng.xml (environment-like settings); @DataProvider feeds many rows of test data from code. @Optional gives a default when the XML has no value.
How do you run tests in parallel? Why parallel=classes?
🔴 ⭐
Set parallel (methods, classes, tests, instances) and thread-count; on one method, invocationCount + threadPoolSize. classes keeps each class's methods on one thread, so its fields and dependsOnMethods stay safe.
Which listeners do you know? How do you register one?
🔴
ITestListener, ISuiteListener, IReporter, IRetryAnalyzer, IAnnotationTransformer. Register with @Listeners (applies to the whole suite!), in testng.xml, or through ServiceLoader.
A failed dependency, a SkipException, a failed @Before… configuration method, or a retried attempt (the earlier try is reported as skipped).
ReportDemoTest (both skip types)
Q73
11. Reporting, build and run
#
Question
Level
Interview answer
Implementation
PDF
73
How do you capture a screenshot on failure and show it in the report?
🟡 ⭐
In @AfterMethod, check that the result failed, take the screenshot, store it on the ITestResult as an attribute, and let the report read it from there.
How do you build a custom HTML report? Why would you?
🔴
Implement IReporter; after the run, TestNG hands you every result. Write one self-contained file with what your team needs: steps, errors, screenshots, filters.
How does Maven run TestNG? How do you run one class, method or group?
🟢
Surefire finds and runs the tests: -Dtest=Class#method, -Dgroups=…. With suiteXmlFiles set, these switches are ignored, which is why this project runs without a suite file.
Common SDET coding questions on strings, arrays, collections and streams, in interview/java/. Each class has the solution, its edge cases and, where one exists, a check against the library way. No browser; the whole group runs in about 2 seconds (mvn clean test -Dgroups=java). Not in the PDF, which covers Selenium and TestNG.
#
Question
Level
Interview answer
Implementation
77
Reverse a string without StringBuilder.reverse().
🟢 ⭐
Copy to a char array and swap from both ends towards the middle, O(n); in real code new StringBuilder(s).reverse(). Avoid result = c + result in a loop (O(n²)).
Topics this lab explains but does not run, and why:
Topic
Why not
Where it is explained
Radio buttons
The practice site has none; they behave like checkboxes except that clicking a selected one does not unselect it
CheckboxTest Javadoc
HTML5 drag and drop
Actions.dragAndDrop has long been unreliable with HTML5 (draggable) drag events in Chrome, so it does not make a dependable example; it works for mouse-based drag (sliders, jQuery UI)
PDF Q34
Table sorting by header click
The practice site's sorting plugin does not load in the browser
WebTableTest
Selenium Grid, Docker, CI
Out of scope for this interview lab; they belong in a production-style project