0% found this document useful (0 votes)
5 views4 pages

Java Selenium Interview Tips & Tricks

The document outlines 15 advanced Java and Selenium interview programs, focusing on handling common exceptions, implementing efficient waits, and managing dynamic elements. Key techniques include retry logic for stale elements, using FluentWait instead of Thread.sleep, and verifying UI elements such as sorting in tables and broken links. Additional topics cover file uploads, window handling, capturing screenshots, and reading JSON data using ObjectMapper.

Uploaded by

Ranish Vj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Java Selenium Interview Tips & Tricks

The document outlines 15 advanced Java and Selenium interview programs, focusing on handling common exceptions, implementing efficient waits, and managing dynamic elements. Key techniques include retry logic for stale elements, using FluentWait instead of Thread.sleep, and verifying UI elements such as sorting in tables and broken links. Additional topics cover file uploads, window handling, capturing screenshots, and reading JSON data using ObjectMapper.

Uploaded by

Ranish Vj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

​15 Tricky Java + Selenium Interview​

​Programs​

​Handling StaleElementReferenceException​
​ccurs when DOM refreshes after locating element. Retry logic helps​
O
handle it gracefully.​

public WebElement retryingFind(By locator) {​



WebElement element = null;​

int attempts = 0;​

while (attempts < 3) {​

try {​

element = [Link](locator);​

break;​

} catch (StaleElementReferenceException e) {​

[Link]("Retrying... attempt " + attempts);​

}​

attempts++;​

}​

return element;​

}​

​FluentWait Instead of [Link]​


Avoid [Link]() using FluentWait with polling interval.​

Wait<WebDriver> wait = new FluentWait<>(driver)​



.withTimeout([Link](30))​

.pollingEvery([Link](2))​

.ignoring([Link]);​

WebElement element = [Link](d -> [Link]([Link]("submit")));​

​Dynamic Dropdown Using Streams​


Use Java Streams to handle dynamic dropdowns elegantly.​

​ist<WebElement> options = [Link]([Link]("//ul/li"));​


L
[Link]()​

.filter(e -> [Link]().equalsIgnoreCase("India"))​

.findFirst()​

.ifPresent(WebElement::click);​

​Highlight Element Before Click​
​se JavaScriptExecutor to visually highlight an element before​
U
performing an action.​

​ebElement ele = [Link]([Link]("login"));​


W
JavascriptExecutor js = (JavascriptExecutor) driver;​

[Link]("arguments[0].[Link]='3px solid #50FA7B'", ele);​

​Verify Sorting in Table​


Compare sorted data from UI with programmatic sorting.​

List<String> names = [Link]([Link]("//table//td[1]"))​



.stream().map(WebElement::getText).collect([Link]());​

List<String> sorted = new ArrayList<>(names);​

[Link](sorted);​

[Link](names, sorted);​

​Capture Broken Links​


Validate hyperlinks using HTTP response codes.​

​ist<WebElement> links = [Link]([Link]("a"));​


L
for (WebElement link : links) {​

String url = [Link]("href");​

if (url == null || [Link]()) continue;​

HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();​

[Link]("HEAD");​

[Link]();​

int code = [Link]();​

if (code >= 400) [Link](url + " is broken: " + code);​

}​

​File Upload (AutoIt or Robot)​


​andle native dialogs using AutoIt or Robot when sendKeys() isn’t​
H
possible.​

​/ Using AutoIt​
/
[Link]().exec("C:\\path\\to\\AutoIt\\[Link]");​

​/ Or using Robot​
/
Robot robot = new Robot();​

StringSelection ss = new StringSelection("C:\\path\\to\\[Link]");​

[Link]().getSystemClipboard().setContents(ss, null);​

[Link](KeyEvent.VK_CONTROL);​

​[Link](KeyEvent.VK_V);​
r
[Link](KeyEvent.VK_CONTROL);​

[Link](KeyEvent.VK_V);​

[Link](KeyEvent.VK_ENTER);​

[Link](KeyEvent.VK_ENTER);​

​File Download Verification​


Ensure the downloaded file exists within a timeout window.​

​ile downloaded = new File([Link]("[Link]") + "/Downloads/[Link]");​


F
new WebDriverWait(driver, [Link](30))​

.until(d -> [Link]());​

[Link]([Link]());​

​Window Handling (Check Title, Then Switch)​


Switch between windows based on title verification.​

​tring parent = [Link]();​


S
for (String handle : [Link]()) {​

[Link]().window(handle);​

if ([Link]().contains("Expected Title")) break;​

}​

[Link]().window(parent);​

​Screenshot with Failed Test Name​


Capture screenshots with test name in the filename for clarity.​

​tring testName = [Link]().getMethodName();​


S
File src = ((TakesScreenshot)driver).getScreenshotAs([Link]);​

String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());​

[Link](src, new File("./screenshots/" + testName + "_" + ts + ".png"));​

​Retry Failed Test Cases (TestNG)​


Use IRetryAnalyzer to rerun failed test cases automatically.​

public class RetryAnalyzer implements IRetryAnalyzer {​



int count = 0, maxTry = 2;​

public boolean retry(ITestResult result) {​

if (count < maxTry) { count++; return true; }​

return false;​

}​

}​

​Scroll Until Element Visible​
Scroll until element is visible using JavaScriptExecutor.​

​ebElement ele = [Link]([Link]("footer"));​


W
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);",​

ele);​

​Wait Until Page Load Completes​


Wait for full DOM readiness using [Link].​

new WebDriverWait(driver, [Link](30))​



.until(d -> ((JavascriptExecutor) d)​

.executeScript("return [Link]").equals("complete"));​

​Capture Browser Console Errors​


Fetch and log JavaScript console errors.​

​ogEntries logs = [Link]().logs().get([Link]);​


L
for (LogEntry entry : logs) {​

[Link]("Console: " + [Link]());​

}​

​Read JSON Using ObjectMapper​


Use Jackson ObjectMapper for easy JSON parsing.​

​bjectMapper mapper = new ObjectMapper();​


O
Map<String, Object> data = [Link](new File("[Link]"), new​

TypeReference<Map<String,Object>>(){});​

String username = (String) [Link]("username");​

Common questions

Powered by AI

A StaleElementReferenceException occurs when the document object model (DOM) changes after a web element has been located, making the reference to that element invalid. To handle this, implementing a retry logic is effective; it attempts to locate the element multiple times until successful or a maximum number of attempts is reached. This is achieved by surrounding the findElement method with a try-catch block inside a loop, wherein a new attempt is made if the exception is caught .

Selenium can capture browser console errors by accessing the browser logs using manage().logs().get(LogType.BROWSER). This capability is useful for identifying JavaScript errors and understanding client-side issues during testing, which might not surface through UI behavior but still impact user experience or indicate underlying problems in the application .

Capturing and logging broken links is crucial in Selenium testing to ensure all navigations and resources on a web page function properly, enhancing user experience and preventing dead ends. Programmatically, this can be achieved by iterating over all link elements, checking HTTP response codes for their respective URLs, and logging those with a status code of 400 or above, indicating broken links .

Using FluentWait is more beneficial than Thread.sleep because it allows for a more dynamic waiting approach where you can specify a polling interval and ignore specific exceptions like NoSuchElementException. FluentWait keeps checking the condition at the defined interval until it returns a true result or the timeout expires, optimizing both waiting time and resource utilization as it doesn't pause thread execution completely like Thread.sleep does .

Switching windows based on title in Selenium can be achieved by iterating over available window handles, switching to each, and checking if the window's title meets the expected condition. This is significant in multi-window scenarios as it allows precise navigation and interaction with specific windows, crucial for testing workflows involving pop-ups or linked documents .

When sendKeys is inadequate for file uploads due to native dialog handling, tools like AutoIt or Java's Robot class can be used. AutoIt executes scripts to automate GUI interactions, while Robot can programmatically simulate keyboard events to paste the file path into dialog boxes and execute the upload process. This approach effectively bypasses limitations of direct web interactions for file input fields .

Scrolling to an element in Selenium using JavaScriptExecutor involves scripting 'arguments[0].scrollIntoView(true)', which brings the element into the visible area of the browser window. This method is particularly useful when elements are present further down the page and cannot be directly interacted with using standard Selenium actions, ensuring reliable interaction with elements by programmatically managing visibility .

Java Streams can be utilized in handling dynamic dropdowns by providing a streamlined way to process a collection of options. By converting the list of dropdown options to a Stream, we can filter desired options using conditions (e.g., equalsIgnoreCase for a specific country), and then perform an action such as click using 'ifPresent', allowing for concise and readable code .

Data sorting in a table can be programmatically verified in Selenium by first extracting the displayed data, sorting it using Java collections, and then comparing the sorted UI data with the programmatically sorted data to ensure consistency. This verification is important for UI testing as it confirms that the application behaves as expected for end users, particularly in views where context and order are critical, such as lists and search results .

To verify a file has been successfully downloaded in Selenium, you can use a WebDriverWait to poll for its existence within a specified directory for a given timeout period. This handles timing issues by checking the file system at regular intervals, ensuring that any delays in the download process are accounted for before asserting the file’s existence .

You might also like