Day 2: Automation Testing Interview Questions: On Weekend
Day 2: Automation Testing Interview Questions: On Weekend
Q. What is Selenium?
Ans : Selenium is an open-source automation testing tool designed for testing web applications. It
allows testers to automate browser actions across multiple platforms and browsers, such as Chrome,
Firefox, and Edge. Selenium supports several programming languages like Java, Python, C#, and
JavaScript for creating test scripts. It is widely used for its flexibility, scalability, and ability to integrate
with frameworks and CI/CD pipelines.
1. Selenium IDE:
3. Selenium Grid:
o Enables parallel and distributed test execution across different machines and
browsers.
Ans :
1. Open Source: Selenium is free to use, making it accessible to individuals and organizations.
2. Cross-Browser Support: It works with all major browsers like Chrome, Firefox, Edge, and Safari.
3. Multi-Language Support: Test scripts can be written in various programming languages such as
Java, Python, C#, and JavaScript.
5. Integration-Friendly: Selenium integrates seamlessly with frameworks like TestNG, JUnit, and CI/CD
tools like Jenkins and Docker.
6. Parallel Testing: With Selenium Grid, tests can run simultaneously on multiple machines and
browsers.
ID
Name
Class Name
Tag Name
Link Text
CSS Selector
XPath
Ans:
1. findElement():
2. findElements():
Key Difference:
Ans : Dynamic web elements can be handled using the following strategies:
o Use functions like contains(), starts-with(), or text() in XPath to locate elements with
dynamic attributes.
o Example:
o Example:
WebElement element = driver.findElement(By.cssSelector("button[id*='submit']"));
3. Explicit Waits:
o Use explicit waits to wait until the element is present, visible, or clickable.
o Example:
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));
4. JavaScript Executor:
js.executeScript("document.getElementById('dynamicElement').click();");
Ans : Selenium provides three types of waits to handle synchronization between the test script and
web elements:
1. Implicit Wait:
o Waits for a specified amount of time for all elements to appear before throwing an
exception.
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
2. Explicit Wait:
o Waits for a specific condition to be met before proceeding with the next step.
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
3. Fluent Wait:
o Similar to explicit wait but allows custom polling frequency and can ignore specific
exceptions.
o Example:
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
Key Difference:
Fluent Wait: Advanced version of explicit wait with custom polling and exception handling.
Ans : Selenium WebDriver provides APIs to interact with different web browsers and platforms. Here
are the commonly used WebDriver APIs:
1. ChromeDriver:
o Example:
WebDriver driver = new ChromeDriver();
2. FirefoxDriver:
3. EdgeDriver:
o Example:
WebDriver driver = new EdgeDriver();
4. SafariDriver:
5. OperaDriver:
Accept an alert:
alert.accept();
Dismiss an alert:
alert.dismiss();
alert.sendKeys("Test Input");
alert.accept();
driver.switchTo().window(windowHandle);
driver.close();
driver.switchTo().window(parentWindow);
wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
Ans : The Page Object Model (POM) is a design pattern in Selenium used to enhance the
maintainability, readability, and reusability of test scripts. It represents each web page of the
application as a separate class.
1. Separation of Concerns:
o The web page elements and their actions are separated from test scripts, making the
code modular and easier to maintain.
2. Class Representation:
o Each page is represented by a class, where web elements are defined as variables,
and actions (methods) are written to interact with those elements.
3. Encapsulation:
o Test scripts do not directly interact with web elements; they use methods provided by
the corresponding page class.
Ans : In Selenium, an iframe (Inline Frame) is an HTML element that allows you to embed another
HTML document within the current document. To interact with elements inside an iframe, you need to
switch the context to the iframe. Selenium provides methods to switch to and from iframes.
1. Switch to an iframe:
You need to switch to the iframe before interacting with the elements inside it. You can switch
to an iframe using several approaches:
o Switch by WebElement:
First, locate the iframe element and then switch to it.
elementInsideIframe.click();
driver.switchTo().frame("parentIframe");
driver.switchTo().frame("nestedIframe");
Example:
driver.switchTo().frame("iframeID");
button.click();
driver.switchTo().defaultContent();
Key Points:
Always ensure you switch back to the main content after interacting with elements inside an
iframe to avoid any context issues.
Ans : In Selenium, file uploads are typically handled using the <input type="file"> HTML element,
which allows users to select a file to upload. Unlike standard form elements, interacting with the file
input requires setting the file path directly into the input field instead of clicking on a "Choose File"
dialog. Selenium provides a way to interact with the file input fields by sending the file path to them.
Explanation:
1. fileInput.sendKeys(): This method sends the path of the file to the input field. You need to
provide the full file path on your system (e.g., "C:/path/to/file.txt").
2. Form Submission (Optional): After the file is uploaded, you may need to submit the form or
trigger a button to complete the upload, depending on the application.
Key Points:
No Dialog Interaction: Selenium doesn't interact with native file dialog boxes (like "Open" or
"Save"). Instead, it directly inputs the file path into the <input type="file"> element.
Absolute File Path: The file path provided must be absolute. Relative paths or network paths
may not work as expected.
Handling Multiple File Uploads:
To upload multiple files (if the input field allows it), you can pass multiple file paths separated by
newline characters:
fileInput.sendKeys("C:/path/to/file1.txt\nC:/path/to/file2.jpg");
This method works for most web applications with file upload features.
Ans: Selenium WebDriver throws various exceptions when errors occur during test execution.
Understanding these exceptions helps in debugging and writing more robust automation scripts. Here
are some of the most common exceptions in Selenium WebDriver:
1. NoSuchElementException
Cause: This exception is thrown when the WebDriver is unable to locate an element using the
given locator.
Solution: Check if the locator is correct, and ensure the element is present on the page. You
may also need to wait for the element to be visible using waits.
Example:
WebElement element = driver.findElement(By.id("nonExistentElement"));
2. ElementNotVisibleException
Cause: This exception occurs when an element is present in the DOM but not visible to the
user (e.g., it may be hidden or covered by another element).
Solution: Ensure that the element is visible or wait for it to be visible using explicit waits.
Example:
WebElement element = driver.findElement(By.id("hiddenElement"));
3. TimeoutException
Cause: Thrown when a command does not complete in the specified time limit (e.g., waiting
for an element to appear).
Solution: Increase the timeout value or use proper waits to ensure the element or condition
has time to load.
Example:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someElement")));
4. StaleElementReferenceException
Cause: Thrown when the element being interacted with is no longer attached to the DOM,
typically after a page refresh or DOM update.
Solution: Re-locate the element after page refresh or DOM change.
Example:
WebElement element = driver.findElement(By.id("someElement"));
element.click(); // May throw StaleElementReferenceException after DOM change
5. NoSuchFrameException
Cause: Thrown when WebDriver is trying to switch to an iframe that doesn't exist.
Solution: Ensure that the iframe exists and use the correct identifier (e.g., index, name, or
WebElement) when switching.
Example:
driver.switchTo().frame("invalidFrame");
6. ElementNotSelectableException
Cause: Thrown when trying to select an element that is not selectable (e.g., a disabled option
in a dropdown).
Solution: Ensure the element is interactable or selectable before performing actions.
Example:
WebElement option = driver.findElement(By.id("dropdownOption"));
option.click(); // Throws ElementNotSelectableException if the option is disabled
7. InvalidElementStateException
Cause: Thrown when trying to interact with an element in an invalid state (e.g., sending keys to
a disabled input field).
Solution: Ensure that the element is in an appropriate state (enabled, clickable, etc.) before
interacting with it.
Example:
WebElement input = driver.findElement(By.id("disabledInput"));
input.sendKeys("Test"); // Throws InvalidElementStateException if input is disabled
8. WebDriverException
Cause: This is a general exception thrown when an unexpected error occurs in WebDriver.
Solution: It could be caused by issues with the WebDriver or browser. Checking the stack
trace and error messages can provide more information.
Example:
driver.get("http://nonExistentPage.com");
G. JavascriptException
Cause: This exception occurs when there is an error executing JavaScript code.
Solution: Review the JavaScript code for errors. Ensure that JavaScript execution is enabled in
the browser.
Example:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("invalid JavaScript code");
10. FileNotFoundException
Cause: Thrown when a file cannot be found (e.g., when dealing with file uploads or
downloading files).
Solution: Ensure the file path provided is correct, and the file exists.
Example:
File file = new File("path/to/nonExistentFile.txt");
11. UnhandledAlertException
Cause: Thrown when there is an unexpected alert on the webpage that was not handled by
the script.
Solution: Handle alerts properly by using the Alert interface to accept or dismiss the alert.
Example:
driver.switchTo().alert().accept(); // Handle unexpected alert
12. SessionNotFoundException
Cause: This exception is thrown when WebDriver cannot find the session that was previously
created (e.g., when the browser is closed prematurely).
Solution: Ensure the WebDriver session is active and not prematurely terminated.
Example:
WebDriver driver = new ChromeDriver();
driver.quit();
driver.get("http://example.com"); // Throws SessionNotFoundException
Ans : A data-driven test can be achieved using either @DataProvider in TestNG or by utilizing the
Apache POI dependency for reading data from external files (like Excel).
@DataProvider (TestNG): This annotation allows you to provide multiple sets of data for a
single test method. TestNG will run the test multiple times with different data provided by the
@DataProvider method.
Example:
@DataProvider(name = "loginData")
public Object[][] loginData() {
return new Object[][] {
{"user1", "password1"},
{"user2", "password2"}
};
}
@Test(dataProvider = "loginData")
public void testLogin(String username, String password) {
// Use username and password for login test
}
Apache POI: You can read data from an Excel sheet using Apache POI to provide dynamic test
data.
Example:
public Object[][] getData() throws IOException {
FileInputStream fis = new FileInputStream("data.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
int cols = sheet.getRow(0).getPhysicalNumberOfCells();
Object[][] data = new Object[rows-1][cols];
</dependency>
2. Create a TestNG Test Class: Create a Java class and annotate it with TestNG annotations
like @Test, @BeforeClass, @AfterClass, etc.
Example:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.Test;
@BeforeClass
public void setup() {
// Initialize WebDriver
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
driver = new ChromeDriver();
driver.get("https://www.example.com");
}
@Test
public void verifyPageTitle() {
// Test logic: verify title
String title = driver.getTitle();
assert title.equals("Example Domain");
}
@AfterClass
public void tearDown() {
// Close the browser
driver.quit();
}
}
3. Run the Tests: You can run your Selenium tests with TestNG via the TestNG XML
configuration or directly from your IDE (e.g., IntelliJ IDEA or Eclipse).
Example of TestNG XML configuration:
<?xml version="1.0" encoding="UTF-8"?>
<suite name="SeleniumSuite">
<test name="TestExample">
<classes>
<class name="SeleniumTestNGExample" />
</classes>
</test>
</suite>
4. Execute the Test: To run the tests, right-click the TestNG XML file or run the test class directly
from your IDE.
Ans: Selenium Grid is a tool that allows you to run your Selenium tests on multiple machines,
browsers, and operating systems simultaneously. It is designed to distribute the test execution across
multiple environments to speed up the testing process and ensure cross-browser and cross-platform
compatibility. Selenium Grid is part of the Selenium suite and can be used to run tests in parallel on
different machines, reducing the time it takes to run large test suites.
1. Hub:
o The Hub is the central point of the grid where test scripts are loaded and distributed to
the nodes.
o The hub is responsible for controlling and managing the test execution across different
nodes.
o Only one hub is required for the grid, and it accepts requests from multiple test scripts.
2. Node:
o Nodes are the machines where the actual test execution takes place.
o Each node is registered with the hub and can be configured to support different
browsers and operating systems.
o You can have multiple nodes running on different machines, and each node can run
tests on different browsers or OS platforms.
3. Test Execution:
o When a test script is executed, the hub receives the request and assigns it to a free
node that matches the desired browser and operating system.
o The node runs the test on the specified browser and sends the results back to the hub,
which then reports them to the test script.
4. Parallel Execution:
o Selenium Grid allows you to run multiple tests in parallel on different nodes. This
means that tests can be executed simultaneously on different browsers or operating
systems, reducing the overall execution time.
Ans : In Selenium, cookies are small pieces of data stored by the browser that contain information
such as login status, session information, preferences, etc. You can handle cookies in Selenium to
manage sessions, handle user logins, and test applications with different user states.
1. Add a Cookie to the Browser: You can add a cookie to the current session using the
addCookie() method of the WebDriver interface.
Example:
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
// Create a cookie
Cookie cookie = new Cookie("user", "JohnDoe");
2. Get All Cookies: You can retrieve all cookies for the current session using the getCookies()
method. This will return a set of all cookies stored for the current session.
Example:
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
driver.quit();
}
}
3. Get a Specific Cookie by Name: You can retrieve a specific cookie by its name using the
getCookieNamed() method.
Example:
4. Delete a Specific Cookie: To delete a specific cookie, use the deleteCookieNamed() method.
You can delete the cookie by specifying its name.
Example:
driver.manage().deleteCookieNamed("user");
5. Delete All Cookies: You can delete all cookies for the current session using the
deleteAllCookies() method. This is useful when you want to clear all session data.
Example:
driver.manage().deleteAllCookies();
Ans:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.edge.EdgeDriver;
if (browser.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
driver = new ChromeDriver();
} else if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "path_to_geckodriver");
driver = new FirefoxDriver();
} else if (browser.equals("edge")) {
System.setProperty("webdriver.edge.driver", "path_to_edgedriver");
driver = new EdgeDriver();
} else {
System.out.println("Unsupported browser");
return;
}
Ans : When writing Selenium tests, it's essential to follow best practices to ensure that your tests are
maintainable, efficient, and robust. Here are some key best practices to follow:
1. Organize Your Test Code
2. Use Descriptive Test Names
3. Wait for Elements
4. Handle Web Elements Properly
5. Avoid Hardcoding Test Data
6. Implement Proper Test Cleanup
7. Make Tests Independent
8. Handle Browser-Specific Issues
6. Use Version Control (Git)
10. Implement Logging
11. Leverage Test Automation Frameworks
12. Use Continuous Integration (CI)
13. Handle Popups and Alerts
14. Take Screenshots on Failure
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
// Optionally, verify the result after the drag and drop (this will depend on the application)
System.out.println("Drag and drop performed successfully.");