0% found this document useful (0 votes)
17 views19 pages

Day 2: Automation Testing Interview Questions: On Weekend

Uploaded by

suresh
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)
17 views19 pages

Day 2: Automation Testing Interview Questions: On Weekend

Uploaded by

suresh
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/ 19

On Weekend

Day 2 : Automation Testing Interview Questions

/Junaid Aziz /Qasim Nazir


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.

Q. What are the components of the Selenium suite?

Ans : The Selenium suite includes the following components:

1. Selenium IDE:

o A browser plugin for recording and playing back test cases.


o Best suited for beginners and quick test case creation.
2. Selenium WebDriver:

o A core component for automating browser actions through programming.


o Supports multiple programming languages like Java, Python, C#, and more.

3. Selenium Grid:

o Enables parallel and distributed test execution across different machines and
browsers.

o Ideal for running large test suites efficiently.


Q. What are the advantages of using Selenium?

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.

4. Cross-Platform Compatibility: It supports different operating systems, including Windows, macOS,


and Linux.

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.

7. Active Community: A large community offers extensive support and updates.

/Junaid Aziz /Qasim Nazir


On Weekend

Q. What are the different types of locators in Selenium?

Ans: Selenium provides the following locators to identify web elements:

 ID

 Name

 Class Name

 Tag Name

 Link Text

 Partial Link Text

 CSS Selector

 XPath

Q. What is the difference between findElement() and findElements()?

Ans:

1. findElement():

o Returns the first matching element based on the specified locator.


o Throws a NoSuchElementException if no element is found.
o Example:
WebElement element = driver.findElement(By.id("username"));

2. findElements():

o Returns a list of all matching elements based on the specified locator.

o Returns an empty list if no matching elements are found.


o Example:
List<WebElement> elements =
driver.findElements(By.className("buttons"));

Key Difference:

 findElement() retrieves a single element, while findElements() retrieves multiple elements as a


list.

Q. How do you handle dynamic web elements in Selenium?

Ans : Dynamic web elements can be handled using the following strategies:

1. Using Dynamic XPath:

o Use functions like contains(), starts-with(), or text() in XPath to locate elements with
dynamic attributes.

o Example:

/Junaid Aziz /Qasim Nazir


On Weekend

WebElement element = driver.findElement(By.xpath("//button[contains(@id,


'submit')]"));

2. Using Dynamic CSS Selectors:

o Leverage partial matches or attribute selectors to locate elements.

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:

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

WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));
4. JavaScript Executor:

o If the element remains undetected, use JavaScript to interact with it directly.


o Example:
JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("document.getElementById('dynamicElement').click();");

Q. What are the different types of waits in Selenium?

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.

o Applies globally to the WebDriver instance.


o Example:

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.

o Suitable for conditions like element visibility, clickability, or presence.


o Example:

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

WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

/Junaid Aziz /Qasim Nazir


On Weekend

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);

WebElement element = wait.until(driver ->


driver.findElement(By.id("dynamicElement")));

Key Difference:

 Implicit Wait: Global and applies to all elements.

 Explicit Wait: Specific to a condition and element.

 Fluent Wait: Advanced version of explicit wait with custom polling and exception handling.

Q. What are the different types of WebDriver APIs available in Selenium?

Ans : Selenium WebDriver provides APIs to interact with different web browsers and platforms. Here
are the commonly used WebDriver APIs:

1. ChromeDriver:

o For automating Google Chrome browser.

o Example:
WebDriver driver = new ChromeDriver();

2. FirefoxDriver:

o For automating Mozilla Firefox browser.


o Example:

WebDriver driver = new FirefoxDriver();

3. EdgeDriver:

o For automating Microsoft Edge browser.

o Example:
WebDriver driver = new EdgeDriver();

4. SafariDriver:

o For automating Safari browser (specific to macOS).


o Example:

/Junaid Aziz /Qasim Nazir


On Weekend

WebDriver driver = new SafariDriver();

5. OperaDriver:

o For automating Opera browser.


6. RemoteWebDriver:

o For running tests on a remote machine or server (e.g., Selenium Grid).


o Example:
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444"),
capabilities);

Q. How do you handle alerts and pop-up windows in Selenium?

Ans : 1.Handling Alerts:


Selenium provides the Alert interface to interact with alerts such as JavaScript alerts, confirmations,
and prompts.

 Accept an alert:

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

alert.accept();

 Dismiss an alert:

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

alert.dismiss();

 Get alert text:

String alertText = driver.switchTo().alert().getText();

 Send input to a prompt alert:

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

alert.sendKeys("Test Input");

alert.accept();

2. Handling Pop-up Windows (Windows or Tabs):


Selenium uses switchTo().window() to handle multiple browser windows or tabs.

 Get current window handle:

String parentWindow = driver.getWindowHandle();

 Switch to a specific window:

for (String windowHandle : driver.getWindowHandles()) {

driver.switchTo().window(windowHandle);

/Junaid Aziz /Qasim Nazir


On Weekend

 Close a window and return to the parent:

driver.close();

driver.switchTo().window(parentWindow);

Using Explicit Waits for Pop-ups:


Ensure the alert or pop-up is present before interacting with it:

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

wait.until(ExpectedConditions.alertIsPresent());

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

alert.accept();

Q. What is the Page Object Model (POM)?

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.

Key Features of POM:

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.

Q. How do you handle iframes in Selenium?

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.

Steps to Handle Iframes in Selenium:

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 index (if there are multiple iframes on the page):


driver.switchTo().frame(0); // Switches to the first iframe

o Switch by name or ID:

/Junaid Aziz /Qasim Nazir


On Weekend

driver.switchTo().frame("iframeNameOrID"); // Switches using the iframe's name or ID

o Switch by WebElement:
First, locate the iframe element and then switch to it.

WebElement iframeElement = driver.findElement(By.id("iframeID"));

driver.switchTo().frame(iframeElement); // Switches to the iframe element

2. Interact with elements inside the iframe:


After switching to the iframe, you can interact with elements just like you would on the main
page.
Example:

WebElement elementInsideIframe = driver.findElement(By.id("elementID"));

elementInsideIframe.click();

3. Switch back to the main content:


Once you are done with the iframe, you need to switch back to the main page to interact with
other elements outside the iframe. You can switch back using:

driver.switchTo().defaultContent(); // Switches back to the main content of the page

4. Switch to a nested iframe:


If the iframe itself contains other iframes (nested iframes), you need to switch to the parent
iframe first, then switch to the nested iframe.

driver.switchTo().frame("parentIframe");

driver.switchTo().frame("nestedIframe");

Example:

// Switch to iframe by name

driver.switchTo().frame("iframeID");

// Interact with an element inside the iframe

WebElement button = driver.findElement(By.id("submitButton"));

button.click();

// Switch back to main content

driver.switchTo().defaultContent();

Key Points:

 switchTo().frame() is used to switch the context to an iframe.

 switchTo().defaultContent() switches back to the main page.

 Always ensure you switch back to the main content after interacting with elements inside an
iframe to avoid any context issues.

/Junaid Aziz /Qasim Nazir


On Weekend

Q. How do you take screenshots in Selenium?

Ans : File src = (TakesScreenshot)driver.getScreenshotAs(OutputType.FILE);


FileUtils.copyFile(src,new File("Location of the file to be saved"));
Q. How do you handle file uploads in Selenium?

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.

Steps to Handle File Uploads in Selenium:


1. Locate the File Upload Input Field:
Find the file input element on the web page where the file is to be uploaded.
2. Send the File Path to the Input Field:
Use the sendKeys() method to provide the file path to the input element. This will simulate the
user selecting a file without needing to interact with a file dialog box.
3. Submit the Form (Optional):
If the file upload requires submitting a form, you can call the submit() method on the form
element or use the submit button.
Example:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FileUploadExample {


public static void main(String[] args) {
// Set up the WebDriver
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com/upload");

// Locate the file input element on the webpage


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

// Send the file path to the file input element


fileInput.sendKeys("C:/path/to/your/file.txt");

// Optionally submit the form (if required)


// fileInput.submit();

// Close the browser


driver.quit();
}
}

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.

/Junaid Aziz /Qasim Nazir


On Weekend

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.

Q. What are some common exceptions in Selenium WebDriver?

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

/Junaid Aziz /Qasim Nazir


On Weekend

 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

/Junaid Aziz /Qasim Nazir


On Weekend

Q. How do you implement a data-driven framework in Selenium?

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];

for (int i = 1; i < rows; i++) {


for (int j = 0; j < cols; j++) {
data[i-1][j] = sheet.getRow(i).getCell(j).getStringCellValue();
}
}
workbook.close();
return data;
}

Q. How do you integrate Selenium with TestNG?


Ans : TestNG is one of the most popular testing frameworks for Selenium because of its powerful
features like parallel test execution, data-driven testing, and detailed reporting.
Steps for Integration:
1. Add TestNG Dependency: If you're using Maven, include the TestNG dependency in your
pom.xml file:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>

/Junaid Aziz /Qasim Nazir


On Weekend

</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;

public class SeleniumTestNGExample {


WebDriver driver;

@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.

/Junaid Aziz /Qasim Nazir


On Weekend

Q. What is Selenium Grid? How does it work?

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.

How Does Selenium Grid Work?

Selenium Grid follows a hub-and-node architecture:

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.

Q. How do you handle cookies in Selenium?

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.

Handling Cookies in Selenium

1. Add a Cookie to the Browser: You can add a cookie to the current session using the
addCookie() method of the WebDriver interface.

/Junaid Aziz /Qasim Nazir


On Weekend

Example:

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

public class SeleniumCookiesExample {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");

// Create a cookie
Cookie cookie = new Cookie("user", "JohnDoe");

// Add the cookie to the browser


driver.manage().addCookie(cookie);

// Verify if the cookie is added


System.out.println("Cookie added: " + driver.manage().getCookieNamed("user"));

// Close the browser


driver.quit();
}
}

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;

public class SeleniumCookiesExample {


public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");

// Get all cookies


Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
System.out.println("Cookie Name: " + cookie.getName());
System.out.println("Cookie Value: " + cookie.getValue());
}

driver.quit();
}
}

/Junaid Aziz /Qasim Nazir


On Weekend

3. Get a Specific Cookie by Name: You can retrieve a specific cookie by its name using the
getCookieNamed() method.

Example:

Cookie cookie = driver.manage().getCookieNamed("user");

System.out.println("Cookie Value: " + cookie.getValue());

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();

Q. How do you perform cross-browser testing with Selenium?

Ans:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.edge.EdgeDriver;

public class CrossBrowserTesting {


public static void main(String[] args) {
WebDriver driver;
String browser = "chrome"; // Replace with desired browser

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;
}

// Perform the test actions


driver.get("https://www.example.com");

/Junaid Aziz /Qasim Nazir


On Weekend

System.out.println("Title of the page: " + driver.getTitle());

// Close the browser


driver.quit();
}
}
Q. What are some best practices for writing Selenium tests?

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

Q. Write a program to select a value from a dropdown list.

Ans : import org.openqa.selenium.By;


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.WebElement;

public class DropdownSelection {


public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

// Initialize the Chrome driver


WebDriver driver = new ChromeDriver();

// Open the webpage with the dropdown


driver.get("https://www.example.com"); // Replace with the actual URL

// Locate the dropdown element by its ID or any other locator


WebElement dropdown = driver.findElement(By.id("dropdownId")); // Replace with the
actual locator

// Create a Select object to interact with the dropdown


Select select = new Select(dropdown);

/Junaid Aziz /Qasim Nazir


On Weekend

// Select a value by visible text


select.selectByVisibleText("Option 1"); // Replace with the actual option text

// Alternatively, you can select by index (0-based) or value:


// select.selectByIndex(1); // Select second option
// select.selectByValue("optionValue"); // Replace with the actual value attribute

// Optionally, verify the selected option


String selectedOption = select.getFirstSelectedOption().getText();
System.out.println("Selected option: " + selectedOption);

// Close the browser


driver.quit();
}
}
Q. Write a program to handle a JavaScript alert.
Ans : import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class HandleAlert {


public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// Initialize the Chrome driver
WebDriver driver = new ChromeDriver();

// Open the webpage that triggers the alert


driver.get("https://www.example.com"); // Replace with actual URL
// Trigger the JavaScript alert (for example, clicking a button)
driver.findElement(By.id("alertButton")).click(); // Replace with actual element locator

// Switch to the alert


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

// Print the text of the alert


System.out.println("Alert Text: " + alert.getText());

// Handle the alert by accepting it (clicking 'OK')


alert.accept();

// Optionally, you can dismiss the alert (clicking 'Cancel') instead:


// alert.dismiss();
// Close the browser
driver.quit();
}
}
Q. Write a program to perform a drag and drop operation.

Ans : import org.openqa.selenium.By;


import org.openqa.selenium.WebDriver;

/Junaid Aziz /Qasim Nazir


On Weekend

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class DragAndDropExample {


public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");

// Initialize the Chrome driver


WebDriver driver = new ChromeDriver();

// Open the webpage with the drag and drop functionality


driver.get("https://www.dhtmlx.com/docs/products/dhtmlxTree/drag-and-drop/"); //
Example URL

// Locate the source element (the item to be dragged)


By sourceLocator = By.xpath("//span[text()='Item 1']"); // Replace with actual locator
By targetLocator = By.id("target"); // Replace with actual target locator

// Perform the drag and drop using Actions class


Actions actions = new Actions(driver);
actions.dragAndDrop(driver.findElement(sourceLocator),
driver.findElement(targetLocator)).perform();

// Optionally, verify the result after the drag and drop (this will depend on the application)
System.out.println("Drag and drop performed successfully.");

// Close the browser


driver.quit();
}
}

/Junaid Aziz /Qasim Nazir

You might also like