0% found this document useful (0 votes)
12 views

Selenium Cheatsheet

The document provides a comprehensive guide on WebDriver methods, including navigation, window handling, element interaction, and advanced user interactions with the Actions class. It also covers XPath locators, JavaScript execution, waits, alert handling, screenshot capturing, file uploads, common exceptions, and edge cases. Additionally, it includes detailed XPath expressions and their usage scenarios, along with CSS selectors for locating elements in Selenium.

Uploaded by

Shubham Kourav
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)
12 views

Selenium Cheatsheet

The document provides a comprehensive guide on WebDriver methods, including navigation, window handling, element interaction, and advanced user interactions with the Actions class. It also covers XPath locators, JavaScript execution, waits, alert handling, screenshot capturing, file uploads, common exceptions, and edge cases. Additionally, it includes detailed XPath expressions and their usage scenarios, along with CSS selectors for locating elements in Selenium.

Uploaded by

Shubham Kourav
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
You are on page 1/ 82

WebDriver Methods

• Navigation Methods:

o driver.get(String url): Opens the specified URL in the browser.

o driver.navigate().to(String url): Navigates to the specified URL.

o driver.navigate().back(): Navigates back in the browser history.

o driver.navigate().forward(): Navigates forward in the browser history.

o driver.navigate().refresh(): Refreshes the current page.

• Window and Frame Handling:

o driver.manage().window().maximize(): Maximizes the browser window.

o driver.manage().window().fullscreen(): Sets the browser to fullscreen mode.

o driver.switchTo().frame(int index): Switches to a frame by index.

o driver.switchTo().frame(String nameOrId): Switches to a frame by name or ID.

o driver.switchTo().frame(WebElement frameElement): Switches to a frame using a


WebElement.

o driver.switchTo().defaultContent(): Switches back to the main document.

o driver.switchTo().parentFrame(): Switches to the parent frame.

o driver.switchTo().window(String windowHandle): Switches to a specific


window/tab.

o driver.getWindowHandle(): Returns the handle of the current window.

o driver.getWindowHandles(): Returns a set of all window handles.

• Element Interaction:

o driver.findElement(By locator): Finds a single WebElement using the specified


locator.

o driver.findElements(By locator): Finds a list of WebElements using the specified


locator.
o element.click(): Clicks on the WebElement.

o element.sendKeys(CharSequence keys): Sends text to the WebElement.

o element.clear(): Clears the text from an input field.

o element.getText(): Retrieves the visible text of the WebElement.

o element.getAttribute(String attributeName): Retrieves the value of the specified


attribute.

o element.isDisplayed(): Checks if the WebElement is visible.

o element.isEnabled(): Checks if the WebElement is enabled.

o element.isSelected(): Checks if the WebElement is selected (e.g., checkbox or


radio button).

o element.submit(): Submits a form.

• Cookies and Storage:

o driver.manage().getCookies(): Retrieves all cookies.

o driver.manage().getCookieNamed(String name): Retrieves a specific cookie by


name.

o driver.manage().addCookie(Cookie cookie): Adds a cookie.

o driver.manage().deleteCookie(Cookie cookie): Deletes a specific cookie.

o driver.manage().deleteCookieNamed(String name): Deletes a cookie by name.

o driver.manage().deleteAllCookies(): Deletes all cookies.

Actions Class (Advanced User Interactions)

• Mouse Actions:

o Actions actions = new Actions(driver): Creates an Actions object.

o actions.click(): Clicks at the current mouse location.

o actions.click(WebElement element): Clicks on a specific WebElement.

o actions.doubleClick(): Double-clicks at the current mouse location.


o actions.doubleClick(WebElement element): Double-clicks on a specific
WebElement.

o actions.contextClick(): Right-clicks at the current mouse location.

o actions.contextClick(WebElement element): Right-clicks on a specific


WebElement.

o actions.dragAndDrop(WebElement source, WebElement target): Drags and drops


an element.

o actions.dragAndDropBy(WebElement source, int xOffset, int yOffset): Drags and


drops an element by an offset.

o actions.moveToElement(WebElement element): Moves the mouse to a specific


WebElement.

o actions.moveByOffset(int xOffset, int yOffset): Moves the mouse by an offset.

• Keyboard Actions:

o actions.sendKeys(CharSequence keys): Sends keys to the active element.

o actions.keyDown(Keys key): Presses a key.

o actions.keyUp(Keys key): Releases a key.

• Build and Perform:

o actions.build(): Builds the action sequence.

o actions.perform(): Executes the action sequence.

Select Class (Dropdown Handling)

• Select select = new Select(WebElement element): Creates a Select object.

• select.selectByVisibleText(String text): Selects an option by visible text.

• select.selectByValue(String value): Selects an option by value attribute.

• select.selectByIndex(int index): Selects an option by index.

• select.deselectAll(): Deselects all options (for multi-select dropdowns).

• select.deselectByVisibleText(String text): Deselects an option by visible text.


• select.deselectByValue(String value): Deselects an option by value attribute.

• select.deselectByIndex(int index): Deselects an option by index.

• select.getOptions(): Returns all options in the dropdown.

• select.getAllSelectedOptions(): Returns all selected options.

• select.getFirstSelectedOption(): Returns the first selected option.

• select.isMultiple(): Checks if the dropdown allows multiple selections.

2. JavaScript Executor

• Executing JavaScript:

o JavascriptExecutor js = (JavascriptExecutor) driver: Creates a JavaScript Executor


object.

o js.executeScript(String script, Object... args): Executes JavaScript code.

o js.executeAsyncScript(String script, Object... args): Executes asynchronous


JavaScript code.

• Common Use Cases:

o Scroll to an element: js.executeScript("arguments[0].scrollIntoView();", element)

o Click an element: js.executeScript("arguments[0].click();", element)

o Highlight an element: js.executeScript("arguments[0].style.border='3px solid


red'", element)

o Get page title: js.executeScript("return document.title;")

o Refresh the page: js.executeScript("history.go(0)")

3. Waits

• Implicit Wait:

o driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)): Waits for


elements to be present for up to 10 seconds.

• Explicit Wait:
o WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)):
Creates an explicit wait object.

o wait.until(ExpectedConditions.visibilityOfElementLocated(By locator)): Waits


until an element is visible.

• Expected Conditions:

o visibilityOfElementLocated(By locator): Waits until an element is visible.

o elementToBeClickable(By locator): Waits until an element is clickable.

o presenceOfElementLocated(By locator): Waits until an element is present in the


DOM.

o textToBePresentInElement(By locator, String text): Waits until the text is present


in the element.

o alertIsPresent(): Waits until an alert is present.

o titleIs(String title): Waits until the page title matches the specified title.

o titleContains(String title): Waits until the page title contains the specified text.

4. Handling Alerts

• Alert alert = driver.switchTo().alert(): Switches to the alert.

• alert.accept(): Accepts the alert.

• alert.dismiss(): Dismisses the alert.

• alert.getText(): Retrieves the text of the alert.

• alert.sendKeys(String text): Sends text to the alert.

5. Taking Screenshots

• TakesScreenshot screenshot = (TakesScreenshot) driver: Creates a TakesScreenshot


object.

• File srcFile = screenshot.getScreenshotAs(OutputType.FILE): Captures the screenshot.

• FileUtils.copyFile(srcFile, new File("screenshot.png")): Saves the screenshot to a file.


6. File Upload

• Use element.sendKeys("path/to/file") to upload a file to an input element of type file.

7. Common Exceptions

• NoSuchElementException: Thrown when an element is not found.

• ElementNotInteractableException: Thrown when an element is not interactable.

• StaleElementReferenceException: Thrown when the element reference is stale.

• TimeoutException: Thrown when a wait condition times out.

• NoSuchWindowException: Thrown when a window is not found.

• NoSuchFrameException: Thrown when a frame is not found.

• NoAlertPresentException: Thrown when no alert is present.

8. Edge Cases

• Handling dynamic elements with XPath or CSS selectors.

• Handling flaky tests with retry mechanisms.

• Handling SSL certificates and insecure pages.

• Handling browser-specific issues (e.g., Edge, Chrome, Firefox).

• Handling CAPTCHA (not automatable, but you can use delays or manual intervention).

This guide should help you prepare thoroughly for your Selenium Java interview. Good luck!

You can now copy this content into a Word document and save it as a .docx file. Let me know if
you need further assistance!

please add all the xpaths finding ways,just add xpaths ways and when should we use it as one
line discription
Here’s a detailed section on XPath and its various ways of locating elements, along with a one-
line description of when to use each approach. You can add this to your existing document.

Miscellaneous:
• To clear input values

webElement.clear();

XPath Locators
XPath (XML Path Language) is a powerful way to locate elements in Selenium. It allows you to
navigate through the HTML structure of a webpage. Below are the different ways to write XPath
expressions and when to use them.

1. Basic XPath

• Syntax: //tagname[@attribute='value']

• Example: //input[@id='username']

• When to Use: Use this when you know the exact attribute (e.g., id, name, class) of the
element.

2. XPath with contains()

• Syntax: //tagname[contains(@attribute, 'partial_value')]

• Example: //input[contains(@class, 'form-control')]

• When to Use: Use this when the attribute value is dynamic or contains a partial static
value.

3. XPath with text()

• Syntax: //tagname[text()='exact_text']
• Example: //button[text()='Submit']

• When to Use: Use this to locate elements based on their visible text.

4. XPath with contains() and text()

• Syntax: //tagname[contains(text(), 'partial_text')]

• Example: //a[contains(text(), 'Login')]

• When to Use: Use this when the text is dynamic or contains a partial static value.

5. XPath with starts-with()

• Syntax: //tagname[starts-with(@attribute, 'starting_value')]

• Example: //input[starts-with(@id, 'user')]

• When to Use: Use this when the attribute value starts with a specific string.

6. XPath with Logical Operators (and, or)

• Syntax: //tagname[@attribute1='value1' and @attribute2='value2']

• Example: //input[@id='username' and @type='text']

• When to Use: Use this when you need to combine multiple conditions to locate an
element.

7. XPath with or

• Syntax: //tagname[@attribute1='value1' or @attribute2='value2']

• Example: //input[@id='username' or @name='username']

• When to Use: Use this when either of the conditions can be true to locate an element.

8. XPath with not()

• Syntax: //tagname[not(@attribute='value')]
• Example: //input[not(@type='hidden')]

• When to Use: Use this to exclude elements with a specific attribute value.

9. XPath with last()

• Syntax: (//tagname[@attribute='value'])[last()]

• Example: (//div[@class='item'])[last()]

• When to Use: Use this to select the last matching element in a list.

10. XPath with position()

• Syntax: (//tagname[@attribute='value'])[position()=n]

• Example: (//div[@class='item'])[position()=2]

• When to Use: Use this to select the nth matching element in a list.

11. XPath with ancestor

• Syntax: //tagname//ancestor::ancestor_tagname

• Example: //input//ancestor::div

• When to Use: Use this to locate an ancestor element of a specific element.

12. XPath with descendant

• Syntax: //tagname//descendant::descendant_tagname

• Example: //div//descendant::input

• When to Use: Use this to locate a descendant element of a specific element.

13. XPath with following-sibling

• Syntax: //tagname[@attribute='value']//following-sibling::sibling_tagname

• Example: //div[@class='item']//following-sibling::div
• When to Use: Use this to locate a sibling element that comes after the current element.

14. XPath with preceding-sibling

• Syntax: //tagname[@attribute='value']//preceding-sibling::sibling_tagname

• Example: //div[@class='item']//preceding-sibling::div

• When to Use: Use this to locate a sibling element that comes before the current
element.

15. XPath with parent

• Syntax: //tagname[@attribute='value']//parent::parent_tagname

• Example: //input[@id='username']//parent::div

• When to Use: Use this to locate the parent element of a specific element.

16. XPath with child

• Syntax: //tagname[@attribute='value']//child::child_tagname

• Example: //div[@class='container']//child::input

• When to Use: Use this to locate a child element of a specific element.

17. XPath with following

• Syntax: //tagname[@attribute='value']//following::following_tagname

• Example: //div[@class='item']//following::input

• When to Use: Use this to locate any element that comes after the current element in the
DOM.

18. XPath with preceding

• Syntax: //tagname[@attribute='value']//preceding::preceding_tagname

• Example: //div[@class='item']//preceding::input
• When to Use: Use this to locate any element that comes before the current element in
the DOM.

19. XPath with Wildcard (*)

• Syntax: //*[@attribute='value']

• Example: //*[@id='username']

• When to Use: Use this when you don’t know the tag name but know the attribute.

20. XPath with Multiple Attributes

• Syntax: //tagname[@attribute1='value1' and @attribute2='value2']

• Example: //input[@id='username' and @type='text']

• When to Use: Use this when you need to combine multiple attributes to uniquely
identify an element.

21. XPath with normalize-space()

• Syntax: //tagname[normalize-space(text())='value']

• Example: //button[normalize-space(text())='Submit']

• When to Use: Use this to ignore leading/trailing spaces in the text of an element.

22. XPath with axes (Advanced Navigation)

• Syntax: //tagname/axis::target_tagname

• Example: //div/child::input

• When to Use: Use this for advanced navigation through the DOM structure.

23. XPath with self

• Syntax: //tagname/self::self_tagname

• Example: //div/self::div
• When to Use: Use this to select the current element itself.

24. XPath with descendant-or-self

• Syntax: //tagname/descendant-or-self::target_tagname

• Example: //div/descendant-or-self::input

• When to Use: Use this to select the current element and all its descendants.

25. XPath with ancestor-or-self

• Syntax: //tagname/ancestor-or-self::target_tagname

• Example: //input/ancestor-or-self::div

• When to Use: Use this to select the current element and all its ancestors.

When to Use XPath?

• Use XPath when:

o Elements do not have unique attributes like id or name.

o You need to traverse the DOM hierarchy (e.g., parent, child, sibling).

o You need to locate elements based on complex conditions (e.g., contains, starts-
with).

o CSS selectors are not sufficient for your use case.

CSS Selectors
CSS Selectors are used to locate elements in Selenium by matching elements based on their
attributes, hierarchy, or state. CSS Selectors are often faster and more efficient than XPath,
especially in modern browsers.
1. Basic CSS Selectors

Tag Name

• Syntax: tagname

• Example: input

• Description: Selects all elements with the specified tag name.

ID

• Syntax: #id

• Example: #username

• Description: Selects an element with the specified id attribute.

Class

• Syntax: .class

• Example: .form-control

• Description: Selects all elements with the specified class attribute.

Attribute

• Syntax: [attribute='value']

• Example: [type='text']

• Description: Selects elements with the specified attribute and value.

2. Combining Selectors

Tag + ID

• Syntax: tagname#id

• Example: input#username

• Description: Selects an element with the specified tag name and id.

Tag + Class

• Syntax: tagname.class

• Example: input.form-control
• Description: Selects an element with the specified tag name and class.

Tag + Attribute

• Syntax: tagname[attribute='value']

• Example: input[type='text']

• Description: Selects an element with the specified tag name and attribute.

3. Hierarchy-Based Selectors

Descendant

• Syntax: ancestor descendant

• Example: div input

• Description: Selects all input elements that are descendants of a div.

Child

• Syntax: parent > child

• Example: div > input

• Description: Selects all input elements that are direct children of a div.

Adjacent Sibling

• Syntax: element + sibling

• Example: label + input

• Description: Selects the input element immediately following a label.

General Sibling

• Syntax: element ~ sibling

• Example: label ~ input

• Description: Selects all input elements that are siblings of a label.

4. Attribute-Based Selectors

Attribute Contains
• Syntax: [attribute*='value']

• Example: [class*='form']

• Description: Selects elements whose attribute contains the specified value.

Attribute Starts With

• Syntax: [attribute^='value']

• Example: [id^='user']

• Description: Selects elements whose attribute starts with the specified value.

Attribute Ends With

• Syntax: [attribute$='value']

• Example: [id$='name']

• Description: Selects elements whose attribute ends with the specified value.

Attribute Contains Word

• Syntax: [attribute~='value']

• Example: [class~='form']

• Description: Selects elements whose attribute contains the specified word (space-
separated).

5. Pseudo-Classes

First Child

• Syntax: :first-child

• Example: div:first-child

• Description: Selects the first child element of its parent.

Last Child

• Syntax: :last-child

• Example: div:last-child

• Description: Selects the last child element of its parent.


Nth Child

• Syntax: :nth-child(n)

• Example: div:nth-child(2)

• Description: Selects the nth child element of its parent.

Nth Last Child

• Syntax: :nth-last-child(n)

• Example: div:nth-last-child(2)

• Description: Selects the nth child element of its parent, counting from the last.

Only Child

• Syntax: :only-child

• Example: div:only-child

• Description: Selects an element that is the only child of its parent.

First of Type

• Syntax: :first-of-type

• Example: div:first-of-type

• Description: Selects the first element of its type within its parent.

Last of Type

• Syntax: :last-of-type

• Example: div:last-of-type

• Description: Selects the last element of its type within its parent.

Nth of Type

• Syntax: :nth-of-type(n)

• Example: div:nth-of-type(2)

• Description: Selects the nth element of its type within its parent.

Nth Last of Type

• Syntax: :nth-last-of-type(n)
• Example: div:nth-last-of-type(2)

• Description: Selects the nth element of its type within its parent, counting from the last.

6. Pseudo-Elements

Before

• Syntax: ::before

• Example: div::before

• Description: Selects the pseudo-element before the content of the selected element.

After

• Syntax: ::after

• Example: div::after

• Description: Selects the pseudo-element after the content of the selected element.

7. State-Based Selectors

Enabled

• Syntax: :enabled

• Example: input:enabled

• Description: Selects enabled input elements.

Disabled

• Syntax: :disabled

• Example: input:disabled

• Description: Selects disabled input elements.

Checked

• Syntax: :checked

• Example: input:checked

• Description: Selects checked radio buttons or checkboxes.


Focus

• Syntax: :focus

• Example: input:focus

• Description: Selects the input element that has focus.

8. Combining Multiple Selectors

AND Condition

• Syntax: selector1.selector2

• Example: input.form-control

• Description: Selects elements that match both selectors.

OR Condition

• Syntax: selector1, selector2

• Example: input, textarea

• Description: Selects elements that match either selector.

When to Use CSS Selectors?

• Use CSS Selectors when:

o You need faster and more efficient element location (CSS is generally faster than
XPath).

o You want to locate elements based on their attributes, classes, or IDs.

o You need to work with modern browsers that optimize CSS Selectors.

o You want to avoid the complexity of XPath.

Example: Using CSS Selectors in Selenium

java

Copy
// Locate by ID

WebElement username = driver.findElement(By.cssSelector("#username"));

// Locate by Class

WebElement formControl = driver.findElement(By.cssSelector(".form-control"));

// Locate by Attribute

WebElement textInput = driver.findElement(By.cssSelector("input[type='text']"));

// Locate by Hierarchy

WebElement childInput = driver.findElement(By.cssSelector("div > input"));

// Locate by Pseudo-Class

WebElement firstChild = driver.findElement(By.cssSelector("div:first-child"));

Robot Class of Java

The Robot Class is part of the java.awt package and is used to simulate keyboard and mouse
actions in Java applications. It is often used in Selenium for handling OS-level pop-ups, file
uploads, and other interactions that cannot be handled directly by Selenium.

1. Constructor

• Syntax: Robot robot = new Robot()

• Description: Creates an instance of the Robot class.

2. Keyboard Actions

keyPress(int keycode)
• Syntax: robot.keyPress(KeyEvent.VK_ENTER)

• Description: Presses a specific key (e.g., ENTER, TAB, SHIFT).

keyRelease(int keycode)

• Syntax: robot.keyRelease(KeyEvent.VK_ENTER)

• Description: Releases a specific key.

keyPress(int keycode) and keyRelease(int keycode) Combination

• Syntax:

java

Copy

robot.keyPress(KeyEvent.VK_CONTROL);

robot.keyPress(KeyEvent.VK_V);

robot.keyRelease(KeyEvent.VK_V);

robot.keyRelease(KeyEvent.VK_CONTROL);

• Description: Simulates key combinations (e.g., CTRL+V for paste).

3. Mouse Actions

mouseMove(int x, int y)

• Syntax: robot.mouseMove(100, 200)

• Description: Moves the mouse pointer to the specified screen coordinates (x, y).

mousePress(int buttons)

• Syntax: robot.mousePress(InputEvent.BUTTON1_DOWN_MASK)

• Description: Presses the mouse button (e.g., left click, right click).

mouseRelease(int buttons)

• Syntax: robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK)

• Description: Releases the mouse button.

mouseWheel(int wheelAmt)
• Syntax: robot.mouseWheel(3)

• Description: Scrolls the mouse wheel (positive for up, negative for down).

4. Delay

delay(int milliseconds)

• Syntax: robot.delay(2000)

• Description: Adds a delay (in milliseconds) between actions.

5. Screen Capture

createScreenCapture(Rectangle screenRect)

• Syntax:

java

Copy

Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());

BufferedImage screenCapture = robot.createScreenCapture(screenRect);

• Description: Captures a screenshot of the entire screen or a specific area.

6. Pixel Color

getPixelColor(int x, int y)

• Syntax: Color pixelColor = robot.getPixelColor(100, 200)

• Description: Retrieves the color of the pixel at the specified screen coordinates (x, y).

7. Auto Delay

setAutoDelay(int milliseconds)

• Syntax: robot.setAutoDelay(500)

• Description: Sets the default delay (in milliseconds) after every action.
getAutoDelay()

• Syntax: int delay = robot.getAutoDelay()

• Description: Retrieves the current auto delay value.

8. Auto Wait For Idle

setAutoWaitForIdle(boolean isOn)

• Syntax: robot.setAutoWaitForIdle(true)

• Description: Enables/disables automatic waiting for the system to become idle.

isAutoWaitForIdle()

• Syntax: boolean isOn = robot.isAutoWaitForIdle()

• Description: Checks if auto-wait-for-idle is enabled.

9. Common KeyEvent Constants

• KeyEvent.VK_ENTER: Represents the ENTER key.

• KeyEvent.VK_TAB: Represents the TAB key.

• KeyEvent.VK_SHIFT: Represents the SHIFT key.

• KeyEvent.VK_CONTROL: Represents the CTRL key.

• KeyEvent.VK_ALT: Represents the ALT key.

• KeyEvent.VK_ESCAPE: Represents the ESC key.

• KeyEvent.VK_SPACE: Represents the SPACE key.

• KeyEvent.VK_BACK_SPACE: Represents the BACKSPACE key.

• KeyEvent.VK_DELETE: Represents the DELETE key.

• KeyEvent.VK_UP: Represents the UP ARROW key.

• KeyEvent.VK_DOWN: Represents the DOWN ARROW key.

• KeyEvent.VK_LEFT: Represents the LEFT ARROW key.

• KeyEvent.VK_RIGHT: Represents the RIGHT ARROW key.


10. Common MouseEvent Constants

• InputEvent.BUTTON1_DOWN_MASK: Represents the left mouse button.

• InputEvent.BUTTON2_DOWN_MASK: Represents the middle mouse button.

• InputEvent.BUTTON3_DOWN_MASK: Represents the right mouse button.

When to Use Robot Class?

• Use the Robot class when:

o You need to handle OS-level pop-ups (e.g., file upload/download dialogs).

o You need to simulate keyboard/mouse actions that Selenium cannot handle.

o You need to capture screenshots of the entire screen.

o You need to interact with non-browser elements (e.g., desktop applications).

Example: File Upload Using Robot Class

java

Copy

Robot robot = new Robot();

// Open file upload dialog

robot.keyPress(KeyEvent.VK_CONTROL);

robot.keyPress(KeyEvent.VK_V);

robot.keyRelease(KeyEvent.VK_V);

robot.keyRelease(KeyEvent.VK_CONTROL);

// Press ENTER to upload

robot.keyPress(KeyEvent.VK_ENTER);
Real Time Selenium Interview Questions (Challenges etc.)

Q.1. Can you explain the practical distinctions between findElement and findElements in the
context of web automation, and share a specific scenario where you chose one over the
other?

Explanation:
In Selenium WebDriver, findElement is used to locate the first web element on a page using
various locators like id, name, classname, xpath, etc., returning a single WebElement. On the
other hand, findElements returns a list of web elements based on the provided locator strategy.
Both methods are affected by ImplicitlyWait to ensure the web elements are present before
interaction.

Reference Link:
https://www.selenium.dev/documentation/webdriver/elements/finders/

Scenario:
In my project, we had to click a unique button on a webpage. For this specific and singular
action, I opted for findElement because it returns a single WebElement, and we were confident
that only one matching element existed. Conversely, when dealing with multiple elements, like
extracting all links on a page, I used findElements to obtain a list of matching elements.

Example using findElement:

// Using findElement

WebElement singleElement = driver.findElement(By.id("buttonId"));

singleElement.click();

Example using findElements:

// Using findElements

List<WebElement> allLinks = driver.findElements(By.tagName("a"));

for (WebElement link : allLinks) {

System.out.println(link.getAttribute("href"));

}
Exception:
I have faced the NoSuchElementException thrown by findElement when the element is not
present in the DOM after reaching the max time applied by the ImplicitWait. To address this, I
always double-check whether I’ve used the correct attributes present in the DOM and ensure
that the WebElement is not inside frames or ShadowRoot/ShadowDOM, as these can impact
the element’s visibility. findElements() does not throw an exception if no elements are found.
Instead, it returns an empty list. To check whether the list of elements returned
by findElements() is empty by checking its size before attempting to interact with.

Q.2. In a real-world project where you implemented the Page Object Model (POM), could you
describe the type of framework you built and elaborate on how this approach improved the
maintainability and efficiency of your test automation suite?

Explanation:
In my project, I established a Hybrid framework by incorporating the Page Object Model (POM)
as a key design pattern. POM is a testing paradigm that prioritizes code maintainability,
reusability, and readability by encapsulating web page interactions within dedicated classes
known as Page Objects.

Why POM?

• Maintainability: POM advocates for a modular structure, where each page or


application component is represented by a distinct Page Object. This design allows
seamless updates and maintenance as alterations to the application are confined to
specific Page Objects.

• Reusability: Through the encapsulation of page-specific actions and elements in Page


Objects, the codebase becomes more reusable across different test cases. This reduction
in redundancy enhances the overall efficiency of the automation code.

• Readability: Test scripts gain clarity and expressiveness as high-level actions on a page
are abstracted into method calls within the corresponding Page Object.

Reference Link:
https://www.selenium.dev/documentation/test_practices/encouraged/page_object_models/

Use Case:
We worked with an e-commerce website with a multi-step checkout process involving distinct
pages such as Cart, Shipping, and Payment. Leveraging the POM, we crafted a Page Object for
each of these pages, encapsulating specific elements and actions. This modular approach
facilitated streamlined test case creation and maintenance.
POM:

Exception Handling:
While implementing, NullPointerException may arise if the driver instance is not correctly
initialized in the Page Object constructor. To mitigate this, I ensured proper initialization in my
base class to prevent such exceptions.

Challenges and Solutions:


Before implementing the Page Object Model (POM), whenever there was a change in the user
interface of our application, it used to be a challenging task. Without POM, we had numerous
classes, and locating the specific class to make the necessary changes was a tedious process.
This made the workflow less productive.
However, with the implementation of the POM design pattern, the scenario improved
significantly. Now, since we have dedicated Page Objects for each page navigation, making
changes has become much simpler. Instead of searching through multiple classes, I could swiftly
locate and modify the required information in a single Page Object. This not only streamlined
the process but also enhanced overall productivity.

The adoption of the Page Object Model significantly bolstered the maintainability and efficiency
of our test automation suite. The structured separation of concerns within the Page Objects
facilitated easy updates and reduced redundancy, resulting in a more robust and scalable
framework.

Q.3. Can you share your experience dealing with dynamic elements in Selenium? Specifically,
how have you successfully managed and interacted with elements on a webpage that change
dynamically, and what strategies or techniques did you employ to ensure reliable test
automation in such scenarios?

Answer:
Dealing with dynamic elements in Selenium is a common task in my projects. This happens
when elements on a webpage change, often because of dynamic content loading.

Use Case:
For example, in a project where I worked on an application like Salesforce, we had a dropdown.
The options in this dropdown changed dynamically based on user interactions or other
asynchronous events.

Handling Exceptions: When dealing with dynamic elements, a common challenge is


the StaleElementReferenceException. This happens if the webpage changes after locating the
dropdown element. To handle this, we used WebDriverWait to wait for the element to become
clickable or present or stalenessOfEle() before interacting with it.

Challenges and Solutions:

• Challenge: Figuring out the right conditions to wait for the dynamic element to be ready
for interaction.

• Solution: Using WebDriverWait with appropriate ExpectedConditions


like elementToBeClickable or presenceOfElementLocated to ensure the element is in the
expected state before performing actions.
Q.4. Describe various wait mechanisms in Selenium, and explain the practical distinctions
between implicit and explicit waits.

Explanation:
In the context of Selenium WebDriver, there are two primary types of waits: Implicit waits and
explicit waits. Implicit waits are designed as a capability in Selenium and are specifically tailored
to the methods findElement() and findElements(). When searching for an element in the
Document Object Model (DOM), if the element is not immediately found, the implicit wait
allows Selenium to continue searching for the element for a maximum time period.

If the element is not found even after this maximum time period, findElement() will throw
a NoSuchElementException, while findElements() returns an empty list. Implicit waits are
generally set once and applied globally. Implicit waits do not affect anything outside of element-
related operations and do not influence the behavior of alerts, frames, windows, or the
behavior of the WebElement itself. In cases where I need to handle these other aspects, I use
explicit waits.

Code Snippet:

public class WaitMechanismsExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("http://leaftaps.com/opentaps/control/mainrl");

// Implicit Wait (applies to all elements)

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

// Explicit Wait for a specific element

WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));

WebElement element =
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("username")));

// Perform actions on the element

element.click();
}

UseCase:

Explicit waits are implemented through two different classes that adhere to the Wait
interface.The FluentWait, is an older implementation, while the subclass of Fluent Wait, known
as WebDriverWait, is the more commonly used form of explicit wait. WebDriverWait extends
FluentWait, and FluentWait implements the Wait interface. Explicit waits are designed to wait
for specific conditions, such as the appearance or disappearance of alerts, the readiness of
frames, or the count of windows. They are especially useful for conditions like element
clickability, dropdown selectability, or checking for the invisibility of elements.

Explicit waits are written very specifically, with conditions defined at each checkpoint in the
code. Unlike implicit waits, where you set the timeout globally, with explicit waits, you specify
the conditions wherever and whenever you need them. WebDriverWait includes a boolean
condition, known as the “until” condition, which you set using the ExpectedConditions class.
This class provides numerous expected conditions to choose from, such as checking for element
visibility, presence, the presence of specific text, or the count of windows. Additionally, common
conditions like stalenessOf(ele) are often used.

Exception:
WebDriverWait can throw a TimeoutException if the defined timeout period is exceeded. The
FluentWait internally utilizes something called a “polling period,” which is set to 500ms by
default. I can adjust this polling period to suit my needs. Essentially, FluentWait continuously
checks the specified conditions at regular intervals (in this case, every 500ms) until the
maximum timeout is reached. If the condition is not met by the time the maximum timeout is
reached, it triggers a TimeoutException.

Q.5. Can you elaborate on the practical distinctions between the close() and quit() methods in
Selenium WebDriver? How do you decide which one to use in different scenarios based on
your hands-on experience?

Explanation:

• close():

• Definition: The close() method closes the current browser window while keeping
the WebDriver instance running.
• Effect: In my project I use this method when I have multiple tabs/windows open,
closing only the current one without terminating the WebDriver session.

• Use Case: It is ideal for scenarios with multiple open tabs/windows, where I want
to close the active one.

• quit():

• Definition: The quit() method closes all browser windows, terminates the
WebDriver session, and releases resources.

• Effect: It is Suitable when I want to end the testing process, ensuring all browser
windows are closed and resources are freed.

• Use Case: It is appropriate for scenarios like where I’ve completed my test suite
or want to ensure a clean shutdown.

Use Case:

• Use close() when:

• Managing multiple browser tabs/windows during the test.

• I want to close only the current tab/window, continuing the test in others.

• Use quit() when:

• Completing my entire test suite or scenario.

• Ensuring all browser windows are closed and WebDriver resources are released.

Decision Criteria:

• Use close() if:

• Dealing with a multi-tab scenario and closing only the current tab/window is
needed.

• Continuing testing in other open tabs/windows.

• Use quit() if:

• Completing the entire testing process.

• Wanting to ensure a clean and complete closure of all browser windows.

Practical Distinctions:

• close() Distinctions:
• Leaves the WebDriver instance running.

• Suitable for managing multiple open tabs/windows.

• Doesn’t completely terminate the WebDriver session.

• quit() Distinctions:

• Terminates the WebDriver session and releases resources.

• Closes all browser windows.

• Ensures a complete closure of the WebDriver instance.

Decision-Making Based on Experience:

• Decide to use close() when:

• Managing multiple browser tabs/windows during the test.

• I want to close only the current browser tab/window.

• Decide to use quit() when:

• Completing my entire test suite or scenario.

• Ensuring a clean and complete closure of all browser windows and releasing
resources.

So In my project, quit() is commonly used at the end of a test script to ensure a clean shutdown,
while close() is used within a test script when managing multiple browser tabs/windows during
the test execution. This approach ensures efficient resource management and a smooth testing
process.

Q.6. How do you handle dropdowns in Selenium when they are implemented using both the
tag and without using the tag? Can you share your approach or code snippets that
demonstrate your experience in dealing with these different dropdown implementations?

Answer:

In Selenium WebDriver, dealing with dropdowns becomes a bit trickier when they deviate from
the standard <select> tag. The typical Select class in Selenium is tailored for <select> tags, and
when faced with a non-standard implementation, it tends to throw exceptions. My approach to
overcoming this challenge involves a step-by-step strategy.

Code Snippet:
public class DropdownWithSelectTag {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();

driver.get("http://leaftaps.com/opentaps/control/main");

WebElement source = driver.findElement(By.id("createLeadForm_dataSourceId"));

//Create a Select class and pass the WebElement

Select dd = new Select(source);

//use the object and call the methods

dd.selectByIndex(2);

Identify the Parent Element:

• Locate the parent element of the dropdown. This is the container that holds the
dropdown values.

Click on the Parent Element:

• Use the appropriate Selenium code to click on the identified parent element. This
action is crucial for triggering the dropdown to display its options.

Handle Dropdown Values Represented as <li> or <span>:

• After clicking on the parent element, observe how the dropdown values are
represented. They might be in <li> or <span> elements.

Code Snippet:

public class DropdownWithoutSelectTag {

public static void main(String[] args) {


WebDriver driver = new ChromeDriver();

driver.get("https://login.salesforce.com/?locale=in");

// Locate the dropdown element and click to reveal options

driver.findElement(By.xpath("//span[text()='Create']")).click();

driver.findElement(By.xpath("//span[text()='Custom Tab']")).click();

Utilize XPath with ‘Following’ Axis:

• Construct XPath expressions using the ‘following’ axis. Starting from the clicked
parent element, dynamically locate and interact with the dropdown elements
based on their parent tag.

Custom Solution – Extended Select:

• In some projects, like the one I’ve worked on, a custom solution named
“Extended Select” has been implemented. When the element is not a
standard <select> tag, we locate the parent element by its locator and then
perform a click. The ‘following’ options in XPath help identify different tag names
based on their text content.

This approach provides a flexible and custom solution for handling non-standard dropdowns. It
allows for dynamic interaction with dropdown elements, ensuring that the automation script
adapts to different implementations encountered during testing.

Q.7. Can you tell me the distinctions between using getText() and getAttribute(), and explain
about the usecase of it?

Explanation:


• getText():

• Definition: The getText() method in Selenium is used to retrieve the visible


text content of a web element.

• Usage: It is specifically designed to extract the text that is visibly


displayed on the webpage.

• getAttribute():

• Definition: The getAttribute() method is used to retrieve the value of a


specified attribute of a web element.

• Usage: It is more versatile, as it allows fetching not only text but also
other attributes like href, class, id, etc.

Use Case:

• Use getText() when:

• If I need to extract the visible text content of an element, such as getting


the text within a <span> or <div> tag.

• Example: Verifying the text displayed on a button or capturing the text of


an error message.

• String text = driver.findElement(By.tagName("h2")).getText();

System.out.println(text);

• Use getAttribute() when:

• You want to fetch attribute values like href, class, id, etc.

• Example: Extracting the value of the “href” attribute from a hyperlink or


retrieving the “class” attribute from an element.

Code Snippet:

// Example using getText()

WebElement element = driver.findElement(By.id("exampleId"));

String visibleText = element.getText();

System.out.println("Visible Text: " + visibleText);


// Example using getAttribute()

String hrefValue = element.getAttribute("href");

System.out.println("Href Value: " + hrefValue);

Challenges and Solutions:

Dynamic Content:

• In cases of dynamic content, text might change based on user interactions. Handling
such scenarios involves dynamic waits and robust synchronization strategies.

• These challenges are tackled by closely examining the HTML structure, adapting code to
handle dynamic content gracefully, and employing explicit waits to ensure that the
elements are ready for interaction before fetching text or attributes.

Q.8. Can you share a specific instance where you had to effectively manage alerts using
Selenium? How did you handle it, and what challenges did you encounter?

I was working on a web application that involved submitting a form, and depending on the data
entered, an alert could be triggered. The alert contained a message confirming the successful
submission or notifying about validation errors.

How I Handled It:

Code Snippet:

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

public class AlertHandlingExample {

public static void main(String[] args) {

WebDriver driver = new ChromeDriver();


driver.get("https://www.leafground.com/alert.xhtml");

// Locate the element that triggers the alert (e.g., a Submit button)

WebElement button = driver.findElement(By.xpath("//span[text()='Show']"));

button.click();

// Use WebDriverWait to wait for the alert to be present

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));

wait.until(ExpectedConditions.alertIsPresent());

// Switch to the alert

Alert alert = driver.switchTo().alert();

// Retrieve the alert message

String alertMessage = alert.getText();

// Perform actions based on the alert message or accept/dismiss the alert

if (alertMessage.contains("success")) {

// Handle success scenario

System.out.println("Success: " + alertMessage);

alert.accept();

} else if (alertMessage.contains("error")) {

// Handle error scenario

System.out.println("Error: " + alertMessage);

alert.dismiss();

}
// Continue with the rest of the test

Exceptions:

1. NoAlertPresentException: This exception might occur if an attempt is made to switch to


an alert when no alert is present.

2. UnhandledAlertException: This exception might occur if there is an unhandled alert on


the page.

Challenges Encountered:

1. Timing Issues:

• Challenge: Alerts might not be immediately present after triggering an action.


Waiting for the alert to be present is crucial.

• Solution: I used WebDriverWait to wait for the alert to be present before


attempting to switch to it.

2. Handling Different Scenarios:

• Challenge: The alert message could indicate success or failure, and the script
needed to handle both scenarios appropriately.

• Solution: I retrieved the alert message using alert.getText() and then


implemented conditional logic to perform actions based on the content of the
message.

Handling alerts effectively is crucial for scenarios where user interactions trigger pop-up alerts.
It requires synchronization to ensure that the alert is present before attempting to interact with
it, and the content of the alert message needs to be considered for proper test flow control.

Q.9. Explain Selenium WebDriver Architecture.

Explanation:

Selenium is an open-source library that can be utilized in multiple programming languages, with
each language having its own corresponding bindings.
For example, when using the Java language binding, the following Java code:

ChromeDriver driver = new ChromeDriver();

This Java code internally calls the Selenium Java implementation, which, in turn, calls W3C
protocol-based requests or JSON wire protocol.

Selenium 4 completely uses the W3C protocol, whereas Selenium 3 and older versions use JSON
protocols.

Technically, it’s more of a REST API calls, with these calls reaching the ChromeDriver, which are
native drivers running on the local machines.

These API requests hit the local server, where the requests are received, processed, and

executed within the attached browser.

The browser can be either the ChromeDriver or Firefox Driver. After execution, the response is
captured and sent back from the ChromeDriver to the language binding as a response.

The Selenium Java bindings then capture this response, and based on the response information,
either as an exception or an outcome, it provides the corresponding result. This is the
fundamental architecture of Selenium’s navigation.

This architecture is true for other browsers like IE, Safari, Opera, or when writing code in Python
or C#.

Q.10. Can you describe how you use the Actions class in Selenium to achieve drag-and-drop
functionality in a web application and provide examples where you have successfully
implemented this technique to enhance test automation?

Explanation: The Actions class in Selenium is used for performing complex user interactions like
mouse and keyboard actions. For drag-and-drop functionality, we utilize
the dragAndDrop method of the Actions class. This allows us to click and hold an element, drag
it to another location, and then release the mouse.

Use Case: In my project while working with Salesforce application I have a web page with a
drag-and-drop feature for arranging items in a list. I want to automate the testing of this
functionality to ensure that the items are rearranged correctly after a drag-and-drop operation.

Code Snippet:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;

public class DragAndDropExample {

public static void main(String[] args) {

ChromeDriver driver = new ChromeDriver();

driver.get("https://www.leafground.com/drag.xhtml;");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

WebElement drag = driver.findElement(By.id("form:conpnl_header"));

WebElement drop = driver.findElement(By.xpath("//div[@id='form:drag']//div"));

Actions builder = new Actions(driver);

builder.dragAndDrop(drag, drop).perform();

Exception Handling: One potential exception I have faced in using Actions class is
the `MoveTargetOutOfBoundsException`. This occurs if the target element is not visible or not in
the viewport, making it impossible for Selenium to perform the drag-and-drop action. I always
ensure the visibility of the target element which mitigates this issue.

Challenges and Solutions:

• Identifying Elements Correctly Identifying the source and target elements


accurately is crucial. I addressed this challenge by using unique and stable
locators, such as IDs or CSS classes, to ensure that the correct elements are
selected.
• Asynchronous Operations In some cases, drag-and-drop actions may trigger
asynchronous operations on the web page. I handled this by incorporating waits
(e.g., WebDriverWait) to ensure that the elements are present and visible before
attempting the drag-and-drop operation.

Q.11. How would you use getWindowHandle() and getWindowHandles() in a practical


scenario, and what distinguishes the two methods in real-world applications?

Explanation:
getWindowHandle() and getWindowHandles() are two different methods in Selenium
WebDriver used for handling multiple browser windows or tabs during test automation.

UseCase:
In my project, I faced a scenario where I have a web application that opens a new browser
window or tab after clicking a link. I want to interact with elements in both the original window
and the newly opened one. In this case, I Used getWindowHandle() to get the handle of the
current window before clicking the link and Use getWindowHandles() after clicking the link to
get all window handle and finally iterate through the handles to switch to the new window and
perform actions.

Code Snippet:

ChromeDriver driver = new ChromeDriver();

driver.get("https://www.leafground.com/window.xhtml");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

//click open button

driver.findElement(By.xpath("//span[text()='Open']")).click();

//get the title of the parent window

String pTitle = driver.getTitle();

System.out.println("Parent Title is : "+pTitle);

//get the window handle

String pWindowHandle = driver.getWindowHandle();

System.out.println(pWindowHandle);
//to get all window handles

Set<String> windowHandles = driver.getWindowHandles();

//to switch to a particular index

List<String> handles = new ArrayList<>(windowHandles);

//switch to the particular window using index

driver.switchTo().window(handles.get(1));

//to print all the window handles

for (String each : windowHandles) {

System.out.println(each);

//child window title

String cTitle = driver.getTitle();

System.out.println(cTitle);

driver.quit();

Exception:
One common exception associated with this code is NoSuchWindowException. This can occur if
the window handle obtained using getWindowHandle() is no longer valid when trying to switch
back.

Challenges and Solutions:

• Challenge 1: Handling dynamic window handles, especially when windows are opened
based on user interactions.
Solution: Implementing a wait mechanism to ensure all windows are available before
getting handles.

• Challenge 2: Dealing with intermittent issues where the new window takes time to load.
Solution: Incorporating explicit waits for elements in the new window to ensure it’s fully
loaded before interacting with it.

Q.12.Describe the steps you would take to handle file uploads using Selenium. Can you share
a specific example where you successfully implemented file upload functionality?
Explanation:
Handling file uploads using Selenium involves interacting with file input elements on a web
page, providing the path to the file to be uploaded, and triggering the upload process.

UseCase:
In my project, I have a web application that allows to upload a profile picture. I want to
automate the process of selecting a file from my local machine and uploading it through the
web application.In this case,I identified the file input element on the web page and used
sendKeys() method to send the local file path to the input element and Submit the form or
trigger the upload process.

Code Snippet:

// Identify the file input element

WebElement fileInput = driver.findElement(By.id("fileInputId"));

// Provide the path to the local file

String filePath = "/path/to/your/file.jpg";

fileInput.sendKeys(filePath);

Exception:
One common exception associated with file uploads is ElementNotInteractableException. This
can occur if the file input element is not visible or not enabled.

Challenges and Solutions:

• Challenge: Dealing with different file input mechanisms (e.g., input type=”file” or
custom upload controls).

• Solution: Identifying the appropriate mechanism used by the application and adapting
the automation script accordingly. In some cases, JavaScript may need to be executed to
trigger the file input.

• Example from Past Experience: In a previous project, we had a feature that allowed
users to upload documents. I used Selenium to automate this process. The challenge
was that the file input element was initially hidden and only became visible after clicking
a button. I addressed this by first clicking the button to reveal the file input, then sending
the file path using sendKeys(), and finally submitting the form. Explicit waits were crucial
to ensure the elements were ready for interaction.
Q.13. How have you utilized WebDriverWait, and in what scenarios did you find it particularly
valuable?

Explanation:
WebDriverWait is a part of the Selenium WebDriver framework that provides a mechanism to
wait for a certain condition to be met before proceeding with the execution. It is particularly
useful for handling particular behaviour of a WebElement in test automation.

UseCase:
In our project, we need to verify the confirmation message to appear after submitting the form.
While automating this scenario, the testcase fails consistently. To resolve the issue, we
WebDriverWait to handle the scenario. We create a WebDriverWait instance with a timeout of
10 seconds and use the until method to wait until the confirmation message becomes visible on
the page. Once the confirmation message is visible, we retrieve the text of the message using
confirmationMessage.getText() and store it in a variable for further verification.

Code Snippet:

WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(10));

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(message)));

Exception:

It’s important to note that WebDriverWait can throw a TimeoutException if the defined timeout
period is exceeded. The FluentWait internally utilizes something called a “polling period,” which
is set to 500ms by default. You can adjust this polling period to suit your needs. Essentially,
FluentWait continuously checks the specified conditions at regular intervals (in this case, every
500ms) until the maximum timeout is reached. If the condition is not met by the time the
maximum timeout is reached, it triggers a TimeoutException.

Challenges and Solutions:


In a web application with dynamic content loading, I encountered issues where the script was
trying to interact with elements before they were fully loaded. By implementing WebDriverWait
with conditions like visibilityOfElementLocated, I improved the script’s reliability. This was
crucial for a seamless automation flow, especially when dealing with dynamic updates on the
page.

Q.14. How have you utilized JUnit and TestNG in your testing practices, and what specific
differences or advantages have you observed between the two in your projects?
Explanation:
JUnit and TestNG are both testing frameworks used in Java for writing and running test cases.
They provide annotations and assertions to structure and validate test code.

UseCase:
In my project, we were tasked with creating and executing test cases for a web application.

Use JUnit or TestNG to annotate test methods. Organize test suites and test dependencies using
the respective framework’s features. Leverage assertions to validate expected outcomes.

Code Snippet:

import org.testng.Assert;

public class MyTest {

@Test

public void testExample() {

// Test logic

String actualResult = "Hello, World!";

String expectedResult = "Hello, World!";

// Assertion

Assert.assertEquals(actualResult, expectedResult, "Test failed: Actual result does not


match expected result");

Differences/Advantages:

• TestNG Advantages:
Flexible Annotations: TestNG provides a broader set of annotations (e.g., @BeforeSuite,
@AfterSuite, @Parameters) allowing more fine-grained control over test execution.
Dependency Management: TestNG supports test dependencies, ensuring that certain
tests run only if the dependent tests pass.
Parallel Execution: TestNG allows parallel execution of test methods, which can
significantly reduce test execution time.

• JUnit Advantages:
Simplicity: JUnit is simpler and has a shallower learning curve, making it a good choice
for smaller projects or teams new to testing frameworks.
Ecosystem: JUnit has a large ecosystem and is widely adopted, making it a common
choice for various Java projects.

Challenges and Solutions:

• Challenge 1: Adapting to different annotation styles and features.


Solution: Understanding the specific needs of the project and selecting the framework
that aligns better with those needs.

• Challenge 2: Handling test dependencies efficiently.


Solution: Leveraging TestNG’s built-in support for dependencies to manage the order of
test execution.

• Example from Past Experience: In a project where parallel test execution was critical
due to time constraints, I opted for TestNG because of its built-in support for parallelism.
This significantly reduced the overall test execution time, allowing us to run a large suite
of tests in a much shorter period. Additionally, TestNG’s annotation flexibility and
dependency management proved beneficial in orchestrating complex test suites with
varying requirements.

Q.15. Can you share your approach for capturing screenshots using Selenium? Walk me
through the steps you would take to capture and save screenshots during automated testing.

Explanation:
Capturing screenshots using Selenium involves utilizing the TakesScreenshot interface to
capture the current state of the WebDriver instance and then saving it as an image file. This is a
valuable practice in automated testing for visual verification and debugging.

UseCase:
In a scenario where we are running a suite of automated tests for a web application, we want
to capture screenshots at critical points, such as after a successful login or when a specific
element fails to load. At this point, we call the captureScreenshot method at key points in my
test scripts to capture screenshots and provide the WebDriver instance and a file path where
the screenshot should be saved.

Code Snippet:

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.OutputType;:

import org.apache.commons.io.FileUtils;

import java.io.File;

public class ScreenshotUtils {

public static void captureScreenshot(WebDriver driver, String screenshotPath) {

try {

File sourceFile = driver.getScreenshotAs(OutputType.FILE);

File destn=new File("./snap/shot.jpg")

FileUtils.copyFile(sourceFile, destn);

} catch (Exception e) {

e.printStackTrace();

// Handle exceptions if needed

Exception: One common exception I have faced with this code is IOException from
FileUtils.copyFile() method. This can occur if there is an issue with the file operation, such as
insufficient permissions or a non-existent destination path.

Challenges and Solutions:

• Challenge: Managing and organizing a large number of screenshots.


• Solution: Dynamically generate file paths based on timestamps or test case names to
avoid overwriting and facilitate organization.

Q.16. Can you share your experience in dealing with iframes and nested iframes while using
Selenium for web automation? Specifically, how have you successfully navigated and
interacted with iframes?

Explanation:
iFrames (Inline Frames) are HTML elements that allow embedding one HTML document inside
another. When dealing with iframes in Selenium, we need to switch the focus of the WebDriver
to the iframe to interact with elements inside it.

UseCase:
In my project, we have a web page that contains an iframe, and within that iframe, there is
another nested iframe. You need to interact with elements inside both iframes. In this case, First
we identify the iframes using methods like driver.switchTo().frame() by using the overloading
methods like index, id, WebElement to switch focus and Perform actions on elements within the
iframes and Switch back to the main window using defaultContent() when done.

Challenge: Dynamic Iframe Loading

• Example: Iframes that load dynamically after some user action. Strategy: Use explicit
waits (WebDriverWait) to ensure the iframe is present before switching to it. For
example:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));

wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("dynamicFrame"));

Code Snippet:

ChromeDriver driver = new ChromeDriver();

driver.get("https://www.leafground.com/frame.xhtml");

driver.manage().window().maximize();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

//switch to the parent frame

WebElement frameEle = driver.findElement(By.xpath("//h5[text()=' Click Me


(Inside Nested frame)']/following::iframe"));
driver.switchTo().frame(frameEle);

//switch to the nested frame

driver.switchTo().frame(0);

//click he button inside this frame

driver.findElement(By.id("Click")).click();

driver.switchTo().defaultContent();

Q.17. Can you share examples of how you’ve effectively utilized TestNG annotations in your
testing projects? Highlight specific scenarios where the use of annotations contributed to the
success of your test automation efforts.

Explanation:

TestNG annotations play a crucial role in structuring and controlling the flow of test execution in
Selenium automation projects. Annotations such
as @Test, @BeforeMethod, @AfterMethod, @BeforeClass, and @AfterClass allow for better
organization and control over test cases.

Use Case:
In my project, we use a framework called TestNG to run our tests. Before we start running tests,
we need to set up some things. We use annotations to tell the framework what to do at
different steps. BeforeSuite: It gets things ready before anything else. we start our report
here. BeforeTest: Once we start, we need to decide what tests we want to run. Here, we set up
details like which Excel sheet to use BeforeClass: Here we focus on specific groups of tests, kind
of like organizing them. We set up details for each group of tests. DataProvider: This provides
data for our tests. BeforeMethod: Before each test, we need to launch the browser and apply
waits. This annotation helps set up things before each test. @Test:This is where the actual
testing happens and we use this annotation to mark them. AfterMethod: After each test, we
need to clean up. This annotation helps with those post-test activities. AfterSuite: Once all tests
are done, We close our report.

So, these annotations are like instructions for our testing framework, helping it to organize,
prepare, and clean up as it runs our tests. They make the whole testing process smoother and
more organized.

Code Snippet:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.*;

public class ECommerceTestSuite {

WebDriver driver;

@BeforeClass

public void setUp() {

// Code for initializing the WebDriver, opening the browser, etc.

driver = new ChromeDriver();

@Test(priority = 1)

public void testUserAuthentication() {

// Test code for user authentication

@Test(priority = 2)

public void testProductSearch() {

// Test code for product search functionality

@AfterClass

public void tearDown() {

// Code for closing the browser and performing cleanup

driver.quit();
}

Challenges and Solutions:

• Challenge: Parallel Execution Achieving parallel execution of tests. TestNG


provides the capability to run tests in parallel, enhancing the overall speed of test
execution. Annotations like @Parameters and @DataProvider can be used to
facilitate data-driven testing in parallel.

Solution: By effectively using TestNG annotations, I was able to create a well-structured test
suite with proper setup, execution order, and teardown, resulting in more maintainable and
scalable test automation projects.

Q.18. Explain the most occurring exception in your project. How will you handle
StaleElementReferenceException?

Explanation:
A “StaleElement” reference occurs when we find an element using driver.findElement(), and
initially, the element is present, returning a WebElement to the Selenium WebDriver Java
implementation. However, when we attempt to interact with the WebElement using methods
like click(), sendKeys(), getAttribute(), or getText(), the element suddenly disappears from the
Document Object Model (DOM) or the page gets reloaded.

This discrepancy between the presence of the element when initially located and its
disappearance when interacted within a fraction of a millisecond or microsecond results in
a StaleElementReferenceException.

To handle this issue, several methods can be employed:

One approach is to wait for the page or grid to reload using Thread.sleep() before attempting to
interact with the element using findElement followed by the desired action.

Another way to handle the issue is, if it occurs frequently and the time required for the reload is
uncertain, a retry logic can be implemented using a try-catch block to handle
the StaleElementReferenceException. In the catch block, you can retry finding the same element
repeatedly with a maximum number of retries or a maximum timeout when encountering
the StaleElementReferenceException.
Another option is to use WebDriverWait with ExpectedConditions. There is a
specific ExpectedCondition called stalenessOf(), which allows you to wait for the staleness of an
element to disappear before starting interaction with the WebElement.

These are different approaches available to handle the StaleElementReferenceException.

Q.19. Can you demonstrate how to construct an XPath to select an element based on its
relationship with a sibling or ancestor element?

Explanation:

XPath locator is used when there is no stable attributes are found for an element in the DOM.
XPath provides several axes that allow you to navigate through the hierarchy of elements in an
HTML document. The following-sibling, preceding-sibling, and ancestor axes are particularly
useful for selecting elements based on their relationship with sibling or ancestor elements.

XPath -Selection using Sibling Axes

Sibling Selection can be done in two ways:

• Using Elder reference to the target element

Syntax:

//tagName[@attribute=’attributeValue’]/following-sibling::tagName of targeted Element

• Using Younger reference to the targeted element

Syntax:

//tagName[@attribute=’attributeValue’]/preceding-sibling::tagName of targeted Element

If I have the following DOM structure,

<div>

<span>Element 1</span>

<span>Element 2</span>

<span>Element 3</span>

</div>

To select the <span> element that follows the first <span> element, I will use the following
XPath:
//span[text() = 'Element 1']/following-sibling::span[1]

To select the element that precedes the third element, you will use the following XPath:

//span[text() = 'Element 3']/preceding-sibling::span[1]

Selecting an ancestor element:

If I have the following HTML structure:

<div id="grandparent">

<div id="parent">

<div id="child">

<span>Target Element</span>

</div>

</div>

</div>

To select the <div> element with an id of “grandparent” that is an ancestor of


the <span> element, I can use the following XPath:

//span[text() = 'Target Element']/ancestor::div[@id = 'grandparent']

Q.20. How would you set up a Selenium test to run in a headless mode for a specific browser
version? Can you talk through the process and the considerations you would have?

Explanation:

“Headless mode” means that the browser will not be visible during execution; it will run in the
background and won’t be visible to the user. However, Selenium’s getScreenShotAs() method
can capture snapshots, and mouse and keyboard actions will be executed just like in a regular,
visible browser.

Here’s how to implement headless mode using ChromeOptions: You should open the
ChromeOptions class and call the addArguments() method, passing the argument "--
headless" to run the browser in the background as expected. When running in headless mode,
you may encounter occasional failures, particularly with click actions or mouse-related actions.
Therefore, it’s advisable to implement a retry mechanisms in your code. In some cases, we have
observed that headless mode can lead to failures, so it’s not recommended for extensive use
unless you have a specific need for it.

TestNG Interview Questions

1. Basic Questions

1. What is TestNG?

• Answer: TestNG (Test Next Generation) is a testing framework inspired by JUnit and
NUnit but introduces new functionalities like annotations, grouping, prioritization, and
parallel execution, making it more powerful and flexible.

2. What are the advantages of TestNG over JUnit?

• Answer:

o Supports annotations like @BeforeSuite, @AfterSuite, @BeforeTest, @AfterTest,


etc.

o Supports grouping of test cases.

o Supports parallel execution of test methods.

o Supports dependency testing using dependsOnMethods.

o Provides detailed HTML reports.

o Supports parameterization using @Parameters and @DataProvider.

3. What are the different annotations in TestNG?

• Answer:

o @Test: Marks a method as a test method.

o @BeforeSuite: Runs before all tests in the suite.

o @AfterSuite: Runs after all tests in the suite.


o @BeforeTest: Runs before any test method in the test tag.

o @AfterTest: Runs after all test methods in the test tag.

o @BeforeClass: Runs before the first test method in the current class.

o @AfterClass: Runs after all test methods in the current class.

o @BeforeMethod: Runs before each test method.

o @AfterMethod: Runs after each test method.

o @BeforeGroups: Runs before the first test method of any group.

o @AfterGroups: Runs after the last test method of any group.

4. How do you define a test method in TestNG?

• Answer: Use the @Test annotation above the method.

java

Copy

@Test

public void testMethod() {

System.out.println("This is a test method.");

5. What is the use of @BeforeMethod and @AfterMethod?

• Answer:

o @BeforeMethod: Runs before each test method. Used for setup (e.g., initializing
objects, opening browsers).

o @AfterMethod: Runs after each test method. Used for cleanup (e.g., closing
browsers, releasing resources).

2. Intermediate Questions

6. How do you prioritize test cases in TestNG?

• Answer: Use the priority attribute in the @Test annotation.

java
Copy

@Test(priority = 1)

public void testCase1() {

System.out.println("This is test case 1.");

7. What is grouping in TestNG?

• Answer: Grouping allows you to categorize test methods into groups and execute them
selectively.

java

Copy

@Test(groups = "smoke")

public void smokeTest() {

System.out.println("This is a smoke test.");

8. How do you execute only specific groups in TestNG?

• Answer: Use the groups attribute in the testng.xml file.

xml

Copy

<test name="Smoke Test">

<groups>

<run>

<include name="smoke"/>

</run>

</groups>

</test>

Run HTML
9. What is the use of dependsOnMethods in TestNG?

• Answer: It ensures that a test method runs only if the specified methods have passed.

java

Copy

@Test

public void login() {

System.out.println("Login test.");

@Test(dependsOnMethods = "login")

public void homePage() {

System.out.println("Home page test.");

10. How do you disable a test method in TestNG?

• Answer: Use the enabled attribute in the @Test annotation.

java

Copy

@Test(enabled = false)

public void disabledTest() {

System.out.println("This test is disabled.");

11. What is the use of @DataProvider in TestNG?

• Answer: @DataProvider is used for parameterization. It supplies data to test methods.

java

Copy

@DataProvider(name = "testData")
public Object[][] provideData() {

return new Object[][] {

{"username1", "password1"},

{"username2", "password2"}

};

@Test(dataProvider = "testData")

public void loginTest(String username, String password) {

System.out.println("Username: " + username + ", Password: " + password);

12. How do you run tests in parallel in TestNG?

• Answer: Use the parallel attribute in the testng.xml file.

xml

Copy

<suite name="Parallel Test Suite" parallel="methods" thread-count="5">

<test name="Parallel Test">

<classes>

<class name="com.example.TestClass"/>

</classes>

</test>

</suite>

Run HTML

3. Advanced Questions

13. What is the use of @Factory in TestNG?


• Answer: @Factory is used to create instances of test classes dynamically.

java

Copy

@Factory

public Object[] createInstances() {

return new Object[] { new TestClass(1), new TestClass(2) };

14. How do you handle exceptions in TestNG?

• Answer: Use the expectedExceptions attribute in the @Test annotation.

java

Copy

@Test(expectedExceptions = ArithmeticException.class)

public void divideByZero() {

int result = 10 / 0;

15. What is the use of @Listeners in TestNG?

• Answer: @Listeners is used to add custom listeners to modify TestNG's behavior (e.g.,
logging, reporting).

java

Copy

@Listeners(CustomListener.class)

public class TestClass {

@Test

public void testMethod() {

System.out.println("Test method.");

}
}

16. How do you generate reports in TestNG?

• Answer: TestNG automatically generates HTML reports in the test-output folder. You can
also use custom listeners like ITestListener or IReporter to create custom reports.

17. What is the use of @Parameters in TestNG?

• Answer: @Parameters is used to pass parameters from the testng.xml file to test
methods.

java

Copy

@Test

@Parameters({"username", "password"})

public void loginTest(String username, String password) {

System.out.println("Username: " + username + ", Password: " + password);

18. How do you rerun failed test cases in TestNG?

• Answer: Use the IRetryAnalyzer interface to retry failed tests.

java

Copy

public class RetryAnalyzer implements IRetryAnalyzer {

private int retryCount = 0;

private static final int maxRetryCount = 3;

@Override

public boolean retry(ITestResult result) {

if (retryCount < maxRetryCount) {

retryCount++;

return true;
}

return false;

@Test(retryAnalyzer = RetryAnalyzer.class)

public void flakyTest() {

System.out.println("This test may fail and retry.");

19. What is the difference between @BeforeTest and @BeforeClass?

• Answer:

o @BeforeTest: Runs before any test method in the <test> tag in the testng.xml file.

o @BeforeClass: Runs before the first test method in the current class.

20. How do you set timeouts for test methods in TestNG?

• Answer: Use the timeOut attribute in the @Test annotation.

java

Copy

@Test(timeOut = 5000)

public void timeoutTest() throws InterruptedException {

Thread.sleep(6000); // This test will fail due to timeout.

4. Scenario-Based Questions

21. How would you test a login functionality using TestNG?

• Answer:

o Use @DataProvider to supply multiple sets of username and password.


o Use @Test to write the login test method.

o Use @BeforeMethod to open the browser and navigate to the login page.

o Use @AfterMethod to close the browser.

22. How would you handle dependencies between test cases?

• Answer: Use dependsOnMethods or dependsOnGroups to ensure test methods run in a


specific order.

23. How would you run tests in parallel for a large test suite?

• Answer: Use the parallel attribute in the testng.xml file with methods, classes,
or tests as the value.

24. How would you generate a custom report in TestNG?

• Answer: Implement the IReporter interface and override the generateReport method to
create a custom report.

25. How would you handle flaky tests in TestNG?

• Answer: Use IRetryAnalyzer to retry failed tests a specified number of times.

How to Explain Project Structure


1. Start with the Purpose of the Project

Briefly explain what the project is about (e.g., "This is an automation framework for testing a
web application using Selenium, TestNG, and Maven").

Mention the key technologies and tools used (e.g., Selenium, TestNG, Maven, Jenkins, Git, etc.).

2. Explain the High-Level Structure

Use a top-down approach to explain the structure. Start with the root folder and then dive into
subfolders.
Highlight the purpose of each folder and how they contribute to the overall framework.

3. Detailed Breakdown of the Project Structure

Here’s an example of a typical Selenium TestNG project structure and how to explain it:

Root Folder

src/main/java: Contains the main Java code for the framework.

pages: Contains Page Object Model (POM) classes for each page of the application.

Example: LoginPage.java, HomePage.java.

utils: Contains utility classes (e.g., WebDriverManager.java, ConfigReader.java).

base: Contains the base class for initializing WebDriver and common methods.

listeners: Contains custom listeners (e.g., CustomListener.java for logging or reporting).

reports: Contains code for generating custom reports.

constants: Contains constant values (e.g., file paths, URLs).

src/test/java: Contains the test code.

tests: Contains test classes (e.g., LoginTest.java, HomeTest.java).


dataproviders: Contains data provider classes for parameterized tests.

suites: Contains TestNG XML files for test suites (e.g., smoke-test.xml, regression-test.xml).

src/test/resources: Contains configuration files and test data.

config: Contains configuration files (e.g., config.properties for environment-specific data).

testdata: Contains test data files (e.g., Excel, JSON, or CSV files).

drivers: Contains browser drivers (e.g., chromedriver.exe, geckodriver.exe).

target: Contains compiled classes and test reports generated by Maven.

pom.xml: The Maven configuration file for managing dependencies and plugins.

test-output: Contains TestNG-generated reports (e.g., emailable-report.html, index.html).

4. Explain Key Components

Page Object Model (POM)

Purpose: To separate test logic from page-specific logic.

Example:
LoginPage.java contains methods for interacting with the login page (e.g., enterUsername(),
clickLoginButton()).

HomePage.java contains methods for interacting with the home page.

Base Class

Purpose: To initialize WebDriver and provide common methods (e.g., openBrowser(),


closeBrowser()).

Example: BaseTest.java contains @BeforeMethod and @AfterMethod annotations for setup and
teardown.

Utilities

Purpose: To provide reusable methods (e.g., reading configuration files, handling WebDriver).

Example: ConfigReader.java reads values from config.properties.

Test Classes

Purpose: To define test cases using TestNG annotations.

Example: LoginTest.java contains test methods for login functionality.

TestNG XML Files

Purpose: To define test suites and control test execution (e.g., grouping, parallel execution).

Example: smoke-test.xml runs all smoke tests.


Configuration Files

Purpose: To store environment-specific data (e.g., URLs, credentials).

Example: config.properties contains browser=chrome, url=https://example.com.

Reports

Purpose: To generate and store test execution reports.

Example: CustomReport.java generates a custom HTML report.

5. Highlight Best Practices

Modularity: Code is divided into reusable components (e.g., pages, utilities).

Scalability: The structure allows easy addition of new tests or pages.

Maintainability: Configuration and test data are stored separately for easy updates.

Reusability: Common methods are placed in utility classes.

Reporting: TestNG and custom reports provide detailed execution results.

6. Example Explanation

Here’s how you can explain your project structure in an interview:

Interviewer: Can you explain your project structure?


You: Sure! My project is a Selenium TestNG framework for automating a web application. It
follows the Page Object Model (POM) design pattern to ensure maintainability and reusability.
Here’s a breakdown of the structure:

src/main/java:

pages: Contains POM classes like LoginPage.java and HomePage.java for interacting with
application pages.

utils: Contains utility classes like WebDriverManager.java for managing WebDriver and
ConfigReader.java for reading configuration files.

base: Contains the BaseTest.java class for initializing WebDriver and common setup/teardown
methods.

listeners: Contains custom listeners for logging and reporting.

src/test/java:

tests: Contains test classes like LoginTest.java and HomeTest.java with TestNG annotations.

dataproviders: Contains data provider classes for parameterized tests.

suites: Contains TestNG XML files like smoke-test.xml for defining test suites.

src/test/resources:
config: Contains config.properties for environment-specific data.

testdata: Contains Excel or JSON files for test data.

drivers: Contains browser drivers like chromedriver.exe.

pom.xml: Manages dependencies and plugins using Maven.

test-output: Contains TestNG-generated reports like emailable-report.html.

This structure ensures modularity, scalability, and maintainability. For example, adding a new
test case is as simple as creating a new method in the appropriate test class and updating the
TestNG XML file if needed.

7. Be Prepared for Follow-Up Questions

How do you handle test data?

"I store test data in Excel or JSON files under src/test/resources/testdata and use data providers
to read it."

How do you manage browser drivers?

"I store browser drivers in src/test/resources/drivers and use WebDriverManager.java to


initialize the appropriate driver based on the configuration."

How do you handle environment-specific configurations?


"I use config.properties to store environment-specific data like URLs and credentials, and
ConfigReader.java to read these values."

Basic Git Commands for Interviews

1. Initializing a Repository

git init

• Purpose: Initializes a new Git repository in the current directory.

• Example:

bash

Copy

git init

2. Cloning a Repository

git clone <repository-url>

• Purpose: Creates a copy of a remote repository on your local machine.

• Example:

bash

Copy

git clone https://github.com/username/repository.git

3. Checking the Status

git status

• Purpose: Shows the status of the working directory (e.g., untracked files, changes to be
committed).

• Example:
bash

Copy

git status

4. Adding Files to Staging Area

git add <file>

• Purpose: Adds a file to the staging area (prepares it for commit).

• Example:

bash

Copy

git add index.html

git add .

• Purpose: Adds all changes in the working directory to the staging area.

• Example:

bash

Copy

git add .

5. Committing Changes

git commit -m "commit message"

• Purpose: Commits the changes in the staging area with a descriptive message.

• Example:

bash

Copy

git commit -m "Added login functionality"


6. Viewing Commit History

git log

• Purpose: Displays the commit history.

• Example:

bash

Copy

git log

git log --oneline

• Purpose: Displays a simplified commit history (one line per commit).

• Example:

bash

Copy

git log --oneline

7. Creating a New Branch

git branch <branch-name>

• Purpose: Creates a new branch.

• Example:

bash

Copy

git branch feature-login

8. Switching Branches

git checkout <branch-name>

• Purpose: Switches to the specified branch.

• Example:
bash

Copy

git checkout feature-login

git checkout -b <branch-name>

• Purpose: Creates a new branch and switches to it.

• Example:

bash

Copy

git checkout -b feature-login

9. Merging Branches

git merge <branch-name>

• Purpose: Merges the specified branch into the current branch.

• Example:

bash

Copy

git merge feature-login

10. Deleting a Branch

git branch -d <branch-name>

• Purpose: Deletes the specified branch.

• Example:

bash

Copy

git branch -d feature-login


11. Pushing Changes to Remote Repository

git push origin <branch-name>

• Purpose: Pushes the local branch to the remote repository.

• Example:

bash

Copy

git push origin feature-login

12. Pulling Changes from Remote Repository

git pull origin <branch-name>

• Purpose: Fetches and merges changes from the remote repository to the local branch.

• Example:

bash

Copy

git pull origin main

13. Fetching Changes from Remote Repository

git fetch origin

• Purpose: Fetches changes from the remote repository without merging.

• Example:

bash

Copy

git fetch origin

14. Viewing Remote Repositories

git remote -v
• Purpose: Displays the list of remote repositories.

• Example:

bash

Copy

git remote -v

15. Stashing Changes

git stash

• Purpose: Temporarily saves changes that are not ready to be committed.

• Example:

bash

Copy

git stash

git stash apply

• Purpose: Applies the most recently stashed changes.

• Example:

bash

Copy

git stash apply

16. Resetting Changes

git reset <file>

• Purpose: Unstages a file while keeping changes in the working directory.

• Example:

bash

Copy
git reset index.html

git reset --hard

• Purpose: Discards all changes in the working directory and staging area.

• Example:

bash

Copy

git reset --hard

17. Reverting a Commit

git revert <commit-hash>

• Purpose: Creates a new commit that undoes the changes of a previous commit.

• Example:

bash

Copy

git revert abc1234

18. Viewing Differences

git diff

• Purpose: Shows the differences between the working directory and the staging area.

• Example:

bash

Copy

git diff

git diff <commit1> <commit2>

• Purpose: Shows the differences between two commits.

• Example:
bash

Copy

git diff abc1234 def5678

19. Tagging

git tag <tag-name>

• Purpose: Creates a tag for a specific commit (e.g., for releases).

• Example:

bash

Copy

git tag v1.0

git push origin <tag-name>

• Purpose: Pushes a tag to the remote repository.

• Example:

bash

Copy

git push origin v1.0

20. Configuring Git

git config --global user.name "Your Name"

• Purpose: Sets the global username for Git.

• Example:

bash

Copy

git config --global user.name "John Doe"

git config --global user.email "[email protected]"


• Purpose: Sets the global email for Git.

• Example:

bash

Copy

git config --global user.email "[email protected]"

21. Viewing Configuration

git config --list

• Purpose: Displays the current Git configuration.

• Example:

bash

Copy

git config --list

22. Ignoring Files

.gitignore

• Purpose: Specifies files and directories to be ignored by Git.

• Example:

bash

Copy

# Ignore all .log files

*.log

# Ignore the node_modules directory

node_modules/
23. Rebasing

git rebase <branch-name>

• Purpose: Reapplies commits on top of another branch.

• Example:

bash

Copy

git rebase main

24. Cherry-Picking

git cherry-pick <commit-hash>

• Purpose: Applies a specific commit from one branch to another.

• Example:

bash

Copy

git cherry-pick abc1234

25. Viewing Remote Branches

git branch -r

• Purpose: Lists all remote branches.

• Example:

bash

Copy

git branch -r

26. Deleting a Remote Branch

git push origin --delete <branch-name>


• Purpose: Deletes a branch from the remote repository.

• Example:

bash

Copy

git push origin --delete feature-login

27. Renaming a Branch

git branch -m <old-name> <new-name>

• Purpose: Renames a branch.

• Example:

bash

Copy

git branch -m feature-login feature-auth

28. Viewing Remote URLs

git remote show origin

• Purpose: Displays detailed information about the remote repository.

• Example:

bash

Copy

git remote show origin

29. Amending the Last Commit

git commit --amend

• Purpose: Modifies the most recent commit (e.g., to change the commit message or add
files).
• Example:

bash

Copy

git commit --amend

30. Cleaning Untracked Files

git clean -f

• Purpose: Deletes untracked files from the working directory.

• Example:

bash

Copy

git clean -f

Real-Time Scenario Based Selenium Interview Questions


for Experience folks
1. Explain a scenario where you encountered a `NoSuchElementException` and how
you resolved it.
2. Describe a time when you had to handle a `StaleElementReferenceException`.
What steps did you take to resolve it?
3. How do you handle an `ElementNotVisibleException` when an element is
present in the DOM but not visible on the page?.
4. Describe a situation where your test failed due to a `TimeoutException`. How did
you address this issue?
5. Can you explain a scenario where an `ElementClickInterceptedException`
occurred and how you resolved it?
6. Discuss how you handled `UnexpectedAlertPresentException` when an
unexpected alert appeared during test execution.
7. Describe a real-time scenario where you had to deal with an
`InvalidSelectorException`. How did you fix the issue?
8. How do you handle a scenario where elements are dynamically loaded and your
test intermittently fails due to synchronization issues?
9. Give an example of how you used Fluent Wait to handle an element that
appeared with a delay.
10. Describe a situation where you had to deal with network latency issues affecting
your test execution. How did you mitigate this?
11. Explain how you handled an issue where an AJAX call caused a race condition in
your test.
12. Describe a time when your test had to interact with an element that had dynamic
IDs or classes. How did you handle it?
13. How do you handle file download functionality in a web application where the
file name and type are dynamic?
14. Discuss a scenario where you had to automate a CAPTCHA. What approach did
you take?
15. Explain how you dealt with a scenario where your tests needed to run across
multiple browsers with different behaviors.
16. Describe how you managed test data for scenarios where data dependencies
were critical for test execution.
17. Give an example of a complex XPath or CSS selector you had to create to interact
with a challenging web element
18. How did you handle browser-specific issues in your Selenium tests? Provide a
specific example.
19. Discuss a situation where you had to automate a web application with frames -
iframes. How did you manage it?
20. Explain how you handled a scenario where your test script needed to interact
with a non-web-based component, like a file upload dialog.
21. Describe how you handled session management and state maintenance in tests
that required login and logout actions.
22. Give an example of a scenario where you used soft assertions to continue test
execution after an assertion failure.

More Questions Topic Wise:


• 𝗦𝗲𝗹𝗲𝗻𝗶𝘂𝗺 𝗪𝗲𝗯𝗗𝗿𝗶𝘃𝗲𝗿 𝗕𝗮𝘀𝗶𝗰 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀
1. What is Selenium?
2. Difference between Selenium 3 and Selenium 4?
3. What are the different types of locators in Selenium?
4. Difference between `findElement()` and `findElements()`?
5. How do you handle dropdowns in Selenium?
6. How to handle multiple windows in Selenium?
7. What is the difference between `get()` and `navigate().to()`?
8. How do you handle alerts and pop-ups?
9. How do you handle frames and iframes?
10. What is the difference between `driver.quit()` and
`driver.close()`?

𝗦𝗲𝗹𝗲𝗻𝗶𝘂𝗺 𝗪𝗲𝗯𝗗𝗿𝗶𝘃𝗲𝗿 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀


11. What are the different types of waits in Selenium?
12. Implicit vs Explicit Wait - What's the difference?
13. What is Fluent Wait, and when do you use it?
14. How do you handle 'StaleElement ReferenceException'?
15. What is JavaScriptExecutor? How do you use it?
16. How do you scroll a webpage using Selenium?
17. How do you take a screenshot in Selenium?
18. How do you handle file uploads in Selenium?
19. How do you validate broken links in Selenium?
20. How do you capture network logs in Selenium?

𝗦𝗲𝗹𝗲𝗻𝗶𝘂𝗺 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗳𝗼𝗿 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀


21. What is the Page Object Model (POM)?
22. What is Page Factory? How is it different from POM?
23. What is the difference between `@FindBy' and
driver.findElement()`?
24. What are Selenium Grid and its advantages?
25. How do you handle dynamic elements in Selenium?
26. What is the role of `Desired capabilities in Selenium?
27. What are the different types of Assertions used in
Selenium?
28. What are the limitations of Selenium WebDriver?
29. How do you integrate Selenium with TestNG
30. What are TestNG Listeners, and how do you implement them?

𝗦𝗲𝗹𝗲𝗻𝗶𝘂𝗺 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 & 𝗗𝗲𝗯𝘂𝗴𝗴𝗶𝗻𝗴 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀


31. How do you run Selenium tests in headless mode?
32. How do you handle authentication pop-ups in Selenium?
33. How to execute parallel tests in Selenium?
34. How do you handle CAPTCHA in Selenium?
35. What are the different ways to maximize a browser
window in Selenium?TestNG?

You might also like