Top Selenium Interview Questions and Answers for 2024
Oct 24, 2024 21 Min Read 46189 Views
(Last Updated)
Testing is a very important phase in the software development lifecycle (SDLC) and thus, Selenium, a powerful automated testing tool is used. Therefore, if you want to get into a testing career, Selenium is the best choice. Before getting into this, you must have good knowledge of it and prepare for the Selenium Interview Questions and Answers.
In this blog, we will cover the most frequently asked Selenium Interview Questions and Answers in 2024. Out of these hand-picked and top interview questions, you’ll definitely come through some of them during your interview. Let’s see these Selenium interview questions and answers in detail which helps you to crack your Selenium Interview.
Table of contents
- Top 45 Selenium Interview Questions and Answers
- Q1: What is Selenium?
- Q2: What are the components of Selenium?
- Q3: What is Selenium WebDriver?
- Q4: What are the advantages of using Selenium WebDriver?
- Q5: What programming languages are supported by Selenium WebDriver?
- Q6: What are the basic steps to create a Selenium WebDriver test case?
- Q7: What is a WebElement?
- Q8: How do you locate a WebElement using Selenium WebDriver?
- Q9: What is the difference between findElement() and findElements() in Selenium WebDriver?
- Q10: What is the difference between getText() and getAttribute() in Selenium WebDriver?
- Selenium WebDriver with Java
- Q11: Why use Java with Selenium WebDriver?
- Q12: What are the prerequisites for using Java with Selenium WebDriver?
- Q13: How do you set up a Java project for Selenium WebDriver?
- Q14: How do you create a WebDriver instance in Java?
- Selenium WebDriver with Java Basics
- Q15: What is Selenium WebDriver with Java?
- Q16: What is Test Automation in Selenium WebDriver with Java?
- Q17: What are the benefits of Test Automation in Selenium WebDriver with Java?
- Q18: What are the prerequisites for learning Selenium WebDriver with Java?
- Q19: What are the different components of Selenium WebDriver with Java?
- Q20: What are the different types of locators in Selenium WebDriver with Java?
- Q21: What is a WebElement in Selenium WebDriver with Java?
- Q22: How do you find a WebElement in Selenium WebDriver with Java?
- Q23: What is the difference between implicit and explicit waits in Selenium WebDriver with Java?
- Advanced Selenium WebDriver with Java Concepts
- Q24: What are the different types of waits in Selenium WebDriver with Java? Provide code examples.
- Q25: What is a fluent wait in Selenium WebDriver with Java? Provide a code example.
- Q26: What is the Page Object Model (POM) in Selenium WebDriver with Java? Provide a code example.
- Q27: What is the advantage of using the Page Object Model (POM) in Selenium WebDriver with Java? Provide a code example.
- Q28: What is a TestNG listener in Selenium WebDriver with Java? Provide a code example.
- Q29: What is a DataProvider in Selenium WebDriver with Java? Provide a code example.
- Q30: What is a WebDriverEventListener in Selenium WebDriver with Java? Provide a code example.
- Q31: What is the difference between getWindowHandle() and getWindowHandles() in Selenium WebDriver with Java? Provide a code example.
- Q32: What is an Action in Selenium WebDriver with Java? Provide a code example.
- Q33: How do you handle dropdown/select elements using Selenium WebDriver?
- Q34: How do you perform mouse hover actions using Selenium WebDriver?
- Q35: How do you capture screenshots using Selenium WebDriver?
- Q36. How do you perform file uploads using Selenium WebDriver?
- Q37. How do you handle frames/iframe elements using Selenium WebDriver?
- Q38. How do you perform scrolling actions using Selenium WebDriver?
- Q39. How do you handle multiple windows/tabs using Selenium WebDriver?
- Q40. How do you perform keyboard actions (e.g., pressing Enter, typing special characters) using Selenium WebDriver?
- Q41. How do you handle JavaScript alerts, confirmations, and prompts using Selenium WebDriver?
- Q42. How do you handle synchronization/wait conditions in Selenium WebDriver?
- Q43. How do you handle checkboxes and radio buttons using Selenium WebDriver?
- Q44. How do you handle pop-up windows and child windows using Selenium WebDriver?
- Q45. How do you handle cookies using Selenium WebDriver?
- Q46. How do you handle dynamic elements on a webpage using Selenium WebDriver?
- Q47. How do you handle synchronization issues with Ajax calls using Selenium WebDriver?
- Q48. How do you handle browser notifications using Selenium WebDriver?
- Q49. How do you handle SSL certificate errors using Selenium WebDriver?
- Q50. How do you handle geolocation prompts using Selenium WebDriver?
- Q51. How do you handle file downloads using Selenium WebDriver?
- Q52. How do you handle drag-and-drop actions using Selenium WebDriver?
- Q53. How do you handle dynamic dropdowns and select options using Selenium WebDriver?
- Q54. What is Cross browser testing?
- Q55. What is Fluent Wait In Selenium WebDriver?
- Q56. What is the difference between driver.close() and driver.quit() methods?
- Q57. Where will you maintain information like URL, login, and password?
- Q58. What is DOM?
- Q59. Explain what is an assertion in Selenium and what are the types of assertions.
- Q60. What are XPath and its types?
- Q61. What is a Framework?
- Q62. What methods can be used to locate the frame?
- Q63. Using a web driver how you can store a value that is a text box?
- Q64. Mention 5 different exceptions you had in the Selenium web driver?
- Q65. Can I navigate back and forth in a browser in Selenium WebDriver?
- Q66. What are the ways to refresh a browser using Selenium WebDriver?
- Q67. How To Resize Browser Window Using Selenium WebDriver?
- Q68. How to find out whether an element is displayed on the web page?
- Q69. How can you find Broken Links on a page using Selenium WebDriver?
- Q70. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?
- Q71. List some scenarios which we cannot automate using Selenium WebDriver?
- Q72. Explain how you can switch back from a frame.
- Q73. How can we get a text of a web element?
- Q74. How to press ENTER key on the text box In Selenium WebDriver?
- Q75. Write steps to automate primary “login” functionality test cases for an application.
- Q76. How to take a Screenshot in Selenium?
- Q77. What is TestNg?
- Q78. What are the advantages of TestNG?
- Q79. How do you run the TestNG script?
- Q80. How to create and run TestNG.xml?
- Q81. How can we create a data-driven framework using TestNG?
- Q82. What is Parameterized testing in TestNG?
- Q83. How to set test case priority in TestNG?
- Q84. What are the annotations available in TestNG?
- Q85. What is TestNG Assert and list out common TestNG Assertions?
- Q86. How torun test cases in parallel using TestNG?
- Q87. How to disable a test case in TestNG?
- Q88. How to skip a @Test method from executionin TestNG?
- Q89. How to Ignore a test case in TestNG?
- Q90. How TestNG allows to state dependencies?
- Q91. What are the different ways to produce reports for TestNG results?
- Q92. What is the use of @Listener annotation in TestNG?
- Q93. How to write regular expression In testng.xml file to search@Test methods containing “smoke” keyword.
- Q94. What is the time unit we specify in test suites and test cases?
- Q95. List out various ways in which TestNG can be invoked.
- Q96. What is the use of @Test(invocationCount=x)?
- Q97. What is the use of @Test(threadPoolSize=x)?
- Q98. What does the test timeout mean in TestNG?
- Q99. What are @Factory and @DataProvider annotations?
- Q100. What is the Page Object Model in Selenium?
- Q101. What is Page Factory?
- Q102. What is the difference between a Page Object Model (POM) and a Page Factory?
- Q103. What are the advantages of the Page Object Model Framework?
- Q104. What are the OOPS Concepts applied in POM?
- Conclusion
- FAQs
- What are the four parameters of Selenium?
- What are the 5 methods in Selenium?
- Is Selenium good for the future?
Top 45 Selenium Interview Questions and Answers
Let’s go through some of the top Selenium interview questions and answers that can be asked by interviewers:
Q1: What is Selenium?
Selenium is an open-source testing tool used for automating web browsers. It provides a suite of tools for testing web applications across various platforms, browsers, and programming languages.
Q2: What are the components of Selenium?
Selenium consists of four main components: Selenium IDE, Selenium WebDriver, Selenium Grid, and Selenium RC.
Q3: What is Selenium WebDriver?
Selenium WebDriver is a tool used for automating web applications. It provides a programming interface to create and execute test cases using various programming languages.
Q4: What are the advantages of using Selenium WebDriver?
The advantages of using Selenium WebDriver include cross-browser compatibility, support for multiple programming languages, easy integration with other testing frameworks, and the ability to automate complex web application workflows.
Q5: What programming languages are supported by Selenium WebDriver?
Selenium WebDriver supports multiple programming languages, including Java, Python, C#, Ruby, and JavaScript.
Q6: What are the basic steps to create a Selenium WebDriver test case?
The basic steps to create a Selenium WebDriver test case include:
- Launching a web browser
- Navigating to a web page
- Interacting with web elements
- Performing actions on web elements
- Verifying expected results
Q7: What is a WebElement?
A WebElement is an object in a web page that can be interacted with using Selenium WebDriver. Examples of web elements include buttons, links, text fields, and dropdown menus.
Q8: How do you locate a WebElement using Selenium WebDriver?
You can locate a WebElement using various methods, such as ID, name, class name, tag name, link text, and partial link text.
Q9: What is the difference between findElement() and findElements() in Selenium WebDriver?
findElement() returns a single WebElement that matches the specified locator, while findElements() returns a list of all WebElements that match the specified locator.
Q10: What is the difference between getText() and getAttribute() in Selenium WebDriver?
getText() returns the visible text of a WebElement, while getAttribute() returns the value of the specified attribute of a WebElement.
Selenium WebDriver with Java
Q11: Why use Java with Selenium WebDriver?
Java is a popular programming language that is widely used in the industry. It provides a robust set of libraries and frameworks that can be used to build powerful test automation frameworks with Selenium WebDriver.
Q12: What are the prerequisites for using Java with Selenium WebDriver?
The prerequisites for using Java with Selenium WebDriver include:
- Java Development Kit (JDK) installed on your machine
- A Java IDE, such as Eclipse or IntelliJ IDEA
- The Selenium WebDriver Java bindings
- The WebDriver executable for the browser you want to test
Q13: How do you set up a Java project for Selenium WebDriver?
You can set up a Java project for Selenium WebDriver by following these steps:
- Create a new Java project in your IDE
- Add the Selenium WebDriver Java bindings to your project’s build path
- Download the WebDriver executable for the browser you want to test
- Create a new WebDriver instance and start automating your tests
Q14: How do you create a WebDriver instance in Java?
You can create a WebDriver instance in Java using the following code:
WebDriver driver = new ChromeDriver();
This creates a new WebDriver instance for the Chrome browser.
Selenium WebDriver with Java Basics
Q15: What is Selenium WebDriver with Java?
Selenium WebDriver with Java is an open-source tool that enables automated testing of web applications in Java programming language. It provides a set of APIs for interacting with web browsers and performing actions on web elements.
Q16: What is Test Automation in Selenium WebDriver with Java?
Test automation in Selenium WebDriver with Java refers to automating the process of testing web applications using the Selenium WebDriver API and the Java programming language. It involves creating test scripts that simulate user interactions with the web application and verify the expected results.
Q17: What are the benefits of Test Automation in Selenium WebDriver with Java?
The benefits of test automation in Selenium WebDriver with Java include:
- Improved testing efficiency and speed
- Reduced testing costs and time-to-market
- Increased test coverage and accuracy
- Improved software quality and reliability
Q18: What are the prerequisites for learning Selenium WebDriver with Java?
The prerequisites for learning Selenium WebDriver with Java include:
- Basic knowledge of programming concepts and Java programming language
- Understanding of HTML, CSS, and JavaScript
- Familiarity with web browsers and web technologies
- Knowledge of software testing concepts and methodologies
Q19: What are the different components of Selenium WebDriver with Java?
The different components of Selenium WebDriver with Java include:
- WebDriver API: A set of APIs for interacting with web browsers
- Selenium Grid: A tool for distributing tests across multiple machines and browsers
- TestNG: A testing framework for test execution and reporting
- Maven: A build automation tool for managing dependencies and building projects
Q20: What are the different types of locators in Selenium WebDriver with Java?
The different types of locators in Selenium WebDriver with Java include:
- ID
- Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- CSS Selector
- XPath
Q21: What is a WebElement in Selenium WebDriver with Java?
A WebElement in Selenium WebDriver with Java is a representation of a web element on a web page, such as a text box, button, or link. It provides methods for interacting with the element, such as clicking, sending keys, or getting its text.
Q22: How do you find a WebElement in Selenium WebDriver with Java?
You can find a WebElement in Selenium WebDriver with Java by using one of the locator strategies provided by the WebDriver API, such as findElement(By.id(“elementId”)). This returns a WebElement instance that represents the located element on the web page.
Q23: What is the difference between implicit and explicit waits in Selenium WebDriver with Java?
Implicit waits in Selenium WebDriver with Java are set globally for the WebDriver instance and specify a maximum time to wait for an element to be found or an action to be performed before throwing a NoSuchElementException or a TimeoutException. Explicit waits, on the other hand, are applied to specific elements and actions and use the WebDriverWait class to wait for a specific condition to be true before proceeding with the execution of the test.
Advanced Selenium WebDriver with Java Concepts
Q24: What are the different types of waits in Selenium WebDriver with Java? Provide code examples.
The different types of waits in Selenium WebDriver with Java include:
- Implicit waits
- Explicit waits
- Fluent waits Implicit wait example:
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit wait example:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“myElement”)));
Fluent wait example:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“myElement”));
}
});
Q25: What is a fluent wait in Selenium WebDriver with Java? Provide a code example.
A fluent wait in Selenium WebDriver with Java is a type of explicit wait that waits for a particular condition to be met with a specific frequency. It provides a flexible way to wait for a certain element to be present, clickable, or invisible.
Fluent wait example:
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“myElement”));
}
});
Q26: What is the Page Object Model (POM) in Selenium WebDriver with Java? Provide a code example.
The Page Object Model (POM) in Selenium WebDriver with Java is a design pattern that separates the web pages of an application from the test code. It involves creating a separate Java class for each web page that contains the web elements and methods to interact with those elements.
Page Object Model (POM) example:
public class LoginPage { private WebDriver driver;
public LoginPage(WebDriver driver) { this.driver = driver;
}
@FindBy(id = “username”)
private WebElement usernameField; @FindBy(id = “password”)
private WebElement passwordField; @FindBy(id = “loginButton”)
private WebElement loginButton;
public void setUsername(String username) { usernameField.sendKeys(username);
}
public void setPassword(String password) { passwordField.sendKeys(password);
}
public void clickLoginButton() { loginButton.click();
}
}
Q27: What is the advantage of using the Page Object Model (POM) in Selenium WebDriver with Java? Provide a code example.
The advantages of using the Page Object Model (POM) in Selenium WebDriver with Java include:
- Improved code maintainability and readability
- Reduced code duplication and test script size
- Increased reusability of code and web elements
- Easy modification of the web pages and elements
Q28: What is a TestNG listener in Selenium WebDriver with Java? Provide a code example.
A TestNG listener in Selenium WebDriver with Java is a class that implements the TestNG listener interface and can be used to customize the behavior of the TestNG test execution. It provides a way to listen to different events that occur during the test execution, such as test start, test failure, test success, etc.
TestNG listener example:
public class MyTestListener implements ITestListener { public void onTestStart(ITestResult result) {
System.out.println(“Test started: ” + result.getName());
}
public void onTestSuccess(ITestResult result) { System.out.println(“Test passed: ” + result.getName());
}
public void onTestFailure(ITestResult result) { System.out.println(“Test failed: ” + result.getName());
}
// … other methods
}
Q29: What is a DataProvider in Selenium WebDriver with Java? Provide a code example.
A DataProvider in Selenium WebDriver with Java is a TestNG feature that allows you to run the same test method multiple times with different sets of data. It is useful when you want to test the same functionality with different input data.
DataProvider example:
@Test(dataProvider = “testData”)
public void loginTest(String username, String password) { LoginPage loginPage = new LoginPage(driver); loginPage.setUsername(username); loginPage.setPassword(password); loginPage.clickLoginButton();
// … verify login success
}
@DataProvider(name = “testData”) public Object[][] testData() {
return new Object[][] {
{ “user1”, “password1” },
{ “user2”, “password2” },
// … more data sets
};
}
Q30: What is a WebDriverEventListener in Selenium WebDriver with Java? Provide a code example.
A WebDriverEventListener in Selenium WebDriver with Java is an interface that defines methods that are called by WebDriver when certain events occur, such as before clicking an element, after clicking an element, before navigating to a new page, after navigating to a new page, etc. It can be used to customize the behavior of WebDriver.
WebDriverEventListener example:
public class MyWebDriverEventListener implements WebDriverEventListener { public void beforeClickOn(WebElement element, WebDriver driver) {
System.out.println(“About to click on: ” + element.getText());
}
public void afterClickOn(WebElement element, WebDriver driver) { System.out.println(“Clicked on: ” + element.gtText());
}
}
Q31: What is the difference between getWindowHandle() and getWindowHandles() in Selenium WebDriver with Java? Provide a code example.
getWindowHandle() method in Selenium WebDriver with Java returns a string handle of the current window or tab, while getWindowHandles() method returns a set of string handles of all open windows or tabs. The getWindowHandle() method is useful when you want to perform an action on the current window or tab, while the getWindowHandles() method is useful when you want to switch to a different window or tab.
Example code to switch to a different window using getWindowHandles():
Set<String> windowHandles = driver.getWindowHandles(); for (String windowHandle : windowHandles) {
if (!windowHandle.equals(currentWindowHandle)) { driver.switchTo().window(windowHandle);
break;
}
}
Q32: What is an Action in Selenium WebDriver with Java? Provide a code example.
An Action in Selenium WebDriver with Java is a class that provides methods to perform complex user interactions, such as dragging and dropping an element, double-clicking an element, hovering over an element, etc. It is useful when you want to simulate user interactions with the web page.
Example code to perform a drag and drop action:
Actions actions = new Actions(driver);
WebElement sourceElement = driver.findElement(By.id(“source”)); WebElement targetElement = driver.findElement(By.id(“target”)); actions.dragAndDrop(sourceElement, targetElement).build().perform();
Q33: How do you handle dropdown/select elements using Selenium WebDriver?
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.support.ui.Select; public class DropdownHandling { public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Find the dropdown/select element
WebElement dropdown = driver.findElement(By.id(“dropdown-id”));
// Create a Select object
Select select = new Select(dropdown);
// Select by visible text select.selectByVisibleText(“Option 1”);
// Select by value
select.selectByValue(“option-2-value”);
// Select by index
select.selectByIndex(2);
// Deselect all options select.deselectAll();
// Perform further actions on the dropdown
// …
// Close the browser driver.quit();
}
}
Q34: How do you perform mouse hover actions using Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions; public class MouseHover { public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Find the element to hover over
WebElement element = driver.findElement(By.id(“element-id”));
// Create an Actions object
Actions actions = new Actions(driver);
// Perform mouse hover action actions.moveToElement(element).perform();
// Perform further actions after the mouse hover
// …
// Close the browser driver.quit();
}
}
Q35: How do you capture screenshots using Selenium WebDriver?
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
public class ScreenshotCapture {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage driver.get(“https://example.com”);
// Capture the screenshot TakesScreenshot screenshot = (TakesScreenshot) driver;
File srcFile = screenshot.getScreenshotAs(OutputType.FILE);
// Save the screenshot to a specific location
File destFile = new File(“path/to/save/screenshot.png”); FileUtils.copyFile(srcFile, destFile);
// Close the browser driver.quit();
}
}
Q36. How do you perform file uploads using Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class FileUpload {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage with a file upload input driver.get(“https://example.com”);
// Find the file upload input element
WebElement fileInput = driver.findElement(By.id(“file-input-id”));
// Provide the file path to upload
String filePath = “path/to/file.txt”; fileInput.sendKeys(filePath);
// Perform further actions after file upload
// …
// Close the browser driver.quit();
}
}
Q37. How do you handle frames/iframe elements using Selenium WebDriver?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FrameHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Switch to a frame by index driver.switchTo().frame(0);
// Switch to a frame by name or ID driver.switchTo().frame(“frame-name”);
// Switch to a frame by WebElement
WebElement frameElement = driver.findElement(By.id(“frame-id”)); driver.switchTo().frame(frameElement);
// Switch back to the default content driver.switchTo().defaultContent();
// Perform further actions within the frame
// …
// Close the browser driver.quit();
}
}
Q38. How do you perform scrolling actions using Selenium WebDriver?
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScrollHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Scroll vertically by pixel
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(“window.scrollBy(0, 500)”);
// Scroll vertically to an element
WebElement element = driver.findElement(By.id(“element-id”)); js.executeScript(“arguments[0].scrollIntoView();”, element);
// Scroll horizontally by pixel js.executeScript(“window.scrollBy(500, 0)”);
// Perform further actions after scrolling
// …
// Close the browser driver.quit();
}
}
Q39. How do you handle multiple windows/tabs using Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Open a new window/tab driver.get(“https://example.com”); driver.switchTo().newWindow(WindowType.WINDOW);
// Get the window handles
Set<String> windowHandles = driver.getWindowHandles();
// Switch to a specific window/tab
String mainWindowHandle = driver.getWindowHandle();
for (String windowHandle : windowHandles) {
if (!windowHandle.equals(mainWindowHandle)) { driver.switchTo().window(windowHandle); break;
}
}
// Close the current window/tab driver.close();
// Switch back to the main window/tab driver.switchTo().window(mainWindowHandle);
// Perform further actions on the main window/tab
// Close the browser driver.quit();
}
}
Q40. How do you perform keyboard actions (e.g., pressing Enter, typing special characters) using Selenium WebDriver?
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class KeyboardActions {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Find an input field element
WebElement inputField = driver.findElement(By.id(“input-field-id”));
// Type text with keyboard actions inputField.sendKeys(“Text to type”);
// Press Enter key
inputField.sendKeys(Keys.ENTER);
// Type special characters with keyboard actions inputField.sendKeys(Keys.CONTROL, “a”); inputField.sendKeys(Keys.BACK_SPACE);
// Perform further actions after keyboard actions
// …
// Close the browser driver.quit();
}
}
Q41. How do you handle JavaScript alerts, confirmations, and prompts using Selenium WebDriver?
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 JavaScriptAlerts {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage with a JavaScript alert driver.get(“https://example.com”);
// Click a button that triggers a JavaScript alert
driver.findElement(By.id(“alert-button”)).click();
// Switch to the alert
Alert alert = driver.switchTo().alert();
// Get the text of the alert
String alertText = alert.getText();
// Accept the alert
alert.accept();
// Dismiss the alert
// alert.dismiss();
// Perform further actions after handling the alert
// …
// Close the browser driver.quit();
}
}
Q42. How do you handle synchronization/wait conditions in Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Synchronization {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Set the maximum wait time in seconds int waitTime = 10;
// Navigate to a webpage driver.get(“https:example.com”);
// Wait for an element to be visible
WebDriverWait wait = new WebDriverWait(driver, waitTime);
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“element-id”)));
// Perform further actions after synchronization
// …
// Close the browser
driver.quit();
}
}
Q43. How do you handle checkboxes and radio buttons using Selenium WebDriver?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckboxAndRadioButton {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Find a checkbox element
WebElement checkbox = driver.findElement(By.id(“checkbox-id”));
// Check the checkbox if it is not selected if (!checkbox.isSelected()) {
checkbox.click();
}
// Find a radio button element
WebElement radioButton = driver.findElement(By.id(“radio-button-id”));
// Select the radio button if it is not selected if (!radioButton.isSelected()) {
radioButton.click();
}
// Perform further actions after checkbox and radio button handling
// …
// Close the browser
driver.quit();
}
}
Q44. How do you handle pop-up windows and child windows using Selenium WebDriver?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class WindowHandling {
public static void main(String[] args) {
System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”); WebDriver driver = new ChromeDriver(); driver.get(“https://example.com”);
// Click a link/button that opens a new window/pop-up driver.findElement(By.id(“new-window-button”)).click();
// Get the window handles
Set<String> windowHandles = driver.getWindowHandles();
// Switch to the new window/pop-up
for (String windowHandle : windowHandles) {
driver.switchTo().window(windowHandle);
if (driver.getTitle().equals(“New Window”)) {
break;
}
}
// Perform actions on the new window/pop-up
// Close the new window/pop-up driver.close();
// Switch back to the main window
String mainWindowHandle = driver.getWindowHandle(); driver.switchTo().window(mainWindowHandle);
// Perform further actions on the main window
// Close the browser
driver.quit();
}
}
Q45. How do you handle cookies using Selenium WebDriver?
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class CookieHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage driver.get(“https:
//example.com”);
// Add a cookie
Cookie cookie = new Cookie(“cookie-name”, “cookie-value”); driver.manage().addCookie(cookie);
// Get all cookies
Set<Cookie> cookies = driver.manage().getCookies();
// Delete a cookie
driver.manage().deleteCookie(cookie);
// Delete all cookies
driver.manage().deleteAllCookies();
// Perform further actions after cookie handling
// …
// Close the browser
driver.quit();
}
}
Q46. How do you handle dynamic elements on a webpage using Selenium WebDriver?
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class DynamicElementHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage driver.get(“https:
//example.com”);
// Wait for a dynamic element to be visible
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(“dynamic-element-id”)));
// Perform further actions on the dynamic element
// …
// Close the browser
driver.quit();
}
}
Q47. How do you handle synchronization issues with Ajax calls using Selenium WebDriver?
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class AjaxHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage driver.get(“https:
//example.com”);
// Wait for the Ajax call to complete
WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.jsReturnsValue(“return jQuery.active == 0”));
// Perform further actions after Ajax call completion
// …
// Close the browser
driver.quit();
}
}
Q48. How do you handle browser notifications using Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class NotificationHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create ChromeOptions instance
ChromeOptions options = new ChromeOptions();
// Disable browser notifications
options.addArguments(“–disable-notifications”);
// Launch Chrome browser with options
WebDriver driver = new ChromeDriver(options);
// Perform actions after disabling notifications
// …
// Close the browser
driver.quit();
}
}
Q49. How do you handle SSL certificate errors using Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class SSLCertificateHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create ChromeOptions instance
ChromeOptions options = new ChromeOptions();
// Accept SSL certificates
options.setAcceptInsecureCerts(true);
// Launch Chrome browser with options
WebDriver driver = new ChromeDriver(options);
// Perform actions after accepting SSL certificates
// …
// Close the browser
driver.quit();
}
}
Q50. How do you handle geolocation prompts using Selenium WebDriver?
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class GeolocationHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create ChromeOptions instance
ChromeOptions options = new ChromeOptions();
// Set geolocation coordinates
options.setExperimentalOption(“geolocation”, “{\”latitude\”: 37.421999, \”longitude\”: – 122.084}”);
// Launch Chrome browser with options
WebDriver driver = new ChromeDriver(options);
// Perform actions after setting geolocation
// …
// Close the browser
driver.quit();
}
}
Q51. How do you handle file downloads using Selenium WebDriver?
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.chrome.ChromeOptions;
public class FileDownloadHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Create ChromeOptions instance
ChromeOptions options = new ChromeOptions();
// Set download directory
options.addArguments(“–download.default_directory=/path/to/download/directory”);
// Launch Chrome browser with options
WebDriver driver = new ChromeDriver(options);
// Perform actions that trigger file download
WebElement downloadButton = driver.findElement(By.id(“download-button”)); downloadButton.click();
// Perform further actions after file download
// …
// Close the browser
driver.quit();
}
}
Q52. How do you handle drag-and-drop actions using Selenium WebDriver?
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 DragAndDropHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage
driver.get(“https:example.com”);
// Find the source and target elements for drag and drop
WebElement sourceElement = driver.findElement(By.id(“source-element”)); WebElement targetElement = driver.findElement(By.id(“target-element”));
// Perform drag and drop action
Actions actions = new Actions(driver); actions.dragAndDrop(sourceElement, targetElement).build().perform();
// Perform further actions after drag and drop
// …
// Close the browser
driver.quit();
}
}
Q53. How do you handle dynamic dropdowns and select options using Selenium WebDriver?
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.support.ui.Select;
public class DropdownHandling {
public static void main(String[] args) {
// Set the path of the ChromeDriver executable System.setProperty(“webdriver.chrome.driver”, “path/to/chromedriver”);
// Launch Chrome browser
WebDriver driver = new ChromeDriver();
// Navigate to a webpage with a dropdown/select element driver.get(“https:
//example.com”);
// Find the dropdown/select element
WebElement dropdown = driver.findElement(By.id(“dropdown-id”));
// Create Select object
Select select = new Select(dropdown);
// Select an option by visible text select.selectByVisibleText(“Option 1”);
// Select an option by value select.selectByValue(“option1”);
// Select an option by index select.selectByIndex(0);
// Perform further actions after dropdown handling
// …
// Close the browser
driver.quit();
}
}
Q54. What is Cross browser testing?
Cross Browser Testing is a type of functional test to check that your web application works as expected in different browsers. A web application can be opened in any browser by the end user. For example, some people prefer to open https://x.com in Firefox browser, while others can be using Chrome browser or IE.
So we need to ensure that the web application will work as expected in all popular browsers so that more people can access and use it. This motive can be fulfilled with Cross Browser Testing of the product.
Q55. What is Fluent Wait In Selenium WebDriver?
FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.
Q56. What is the difference between driver.close() and driver.quit() methods?
The purpose of these two methods (driver.close and driver.quit) is almost same. Both allow us to close a browser but still, there is a difference.
Q57. Where will you maintain information like URL, login, and password?
These type of information which are used very often and change as per the authorization and environment should always be maintained in a separate file. In case the user hardcore it into the code system, then the user has to change it in every file which has its reference.
Q58. What is DOM?
The document object represents the whole HTML document.
When the HTML document is loaded in the browser, it becomes a document object. It is the root element that represents the HTML document. It has properties and methods. With the help of document objects, we can add dynamic content to our web page.
Q59. Explain what is an assertion in Selenium and what are the types of assertions.
The actual result is compared with the expected result with the help of Assertion. It means verification is done to check if the state of the application is the same as what we are expecting or not. For creating assertion we are going to use the Assert class provided by TestNG.
There are two types of Assertion:-
Hard Assertions.
Soft assertions.
Q60. What are XPath and its types?
XPath stands for XML(eXtensible Markup Language) Path. Using XPath we can navigate to any element in an XML document. Since XML is a component of HTML, XPaths can be used to find web elements on any web page.
There are two types of XPath:
1. Relative XPath
2. Absolute XPath
Q61. What is a Framework?
A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. However, an optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.
Q62. What methods can be used to locate the frame?
Basically, we can switch over the elements and handle frames in Selenium using 3 ways.
- By Index
- By Name or Id
- By Web Element
Q63. Using a web driver how you can store a value that is a text box?
You can use the following command to store a value which is a text box using the web driver:
driver.findElement(By.id(“your Textbox”)).sendKeys(“your keyword”);
Q64. Mention 5 different exceptions you had in the Selenium web driver?
The 5 different exceptions you had in Selenium web drivers are:
- WebDriverException
- NoAlertPresentException
- NoSuchWindowException
- NoSuchElementException
- TimeoutException
Q65. Can I navigate back and forth in a browser in Selenium WebDriver?
We use Navigate interface to navigate back and forth in a browser. It has methods to move back, forward as well as refresh a page:
driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history
driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history
driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements
driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL.
Q66. What are the ways to refresh a browser using Selenium WebDriver?
There are multiple ways to refresh a page in Selenium:
Using driver.navigate().refresh() command as mentioned in the question 45
Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
Using sendKeys(Keys.F5) on any textbox on the webpage.
Q67. How To Resize Browser Window Using Selenium WebDriver?
To resize the browser window to particular dimensions, we use the ‘Dimension’ class to resize the browser window or driver.manage().window().maximize();
Q68. How to find out whether an element is displayed on the web page?
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels, etc.
isDisplayed()
boolean elePresent = driver.findElement(By.xpath(“xpath”)).isDisplayed();
isSelected()
boolean eleSelected= driver.findElement(By.xpath(“xpath”)).isSelected();
isEnabled()
boolean eleEnabled= driver.findElement(By.xpath(“xpath”)).isEnabled();
Q69. How can you find Broken Links on a page using Selenium WebDriver?
public void brokenLink(String url) {
try {
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.connect();
int respCode = httpConnection.getResponseCode();
if (respCode >= 400) {
System.out.println(url + ” is broken and its responsecode is ” + respCode);
} else {
System.out.println(url + ” is Valid and its responsecode is ” + respCode);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Q70. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”);
Q71. List some scenarios which we cannot automate using Selenium WebDriver?
- Bitmap comparison is not possible using Selenium WebDriver
- Automating Captcha is not possible using Selenium WebDriver
- We can not read bar code using Selenium WebDriver
Q72. Explain how you can switch back from a frame.
To switch back from a frame use method defaultContent()
Syntax-driver.switchTo().defaultContent();
Q73. How can we get a text of a web element?
Using getText();
Q74. How to press ENTER key on the text box In Selenium WebDriver?
To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.
driver.findElement(By.xpath(“xpath”)).sendKeys(Keys.ENTER);
Q75. Write steps to automate primary “login” functionality test cases for an application.
Step 1) Understand the project requirement.
Step 2) Identify the Test scenarios
Step 3) Prepare a data input file with the data corresponding to each scenario
Step 4) Launch the tool from the program.
Step 5) Identify the username, password, and login buttons.
Step 6) Verify that the error message for negative scenarios is the same as the success message for positive test -scenarios.
Q76. How to take a Screenshot in Selenium?
Step 1) Convert web driver object to TakeScreenshot
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
Step 2) Call getScreenshotAs method to create image file
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Step 3) Copy file to Desired Location
//Move image file to new destination
File DestFile=new File(fileWithPath);
//Copy file at destination
FileUtils.copyFile(SrcFile, DestFile);
Q77. What is TestNg?
TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration testing.
Q78. What are the advantages of TestNG?
TestNG has the following advantages:
1) Firstly, TestNG is capable of producing reports automatically with all the necessary information such as failed tests, passed tests, test execution times, etc.
2) Secondly, TestNG makes use of annotations such as @BeforeMethod, @Test, etc., which are easily understandable as their naming is after their working.
3) Thirdly, TestNG provides a grouping of methods by which we can group multiple methods as one unit. In other words, Grouping performs operations on all the tests in a group at once rather than individually.
4) Fourthly, TestNG provides a test method parameterization, which means we can provide parameters in the TestNG and call the function repeatedly with different values. Moreover, parameterization helps in data-driven testing in TestNG.
5) Fifthly, TestNG provides the prioritization of methods. In other words, by defining the priorities of the methods in TestNG, we can alter the default execution sequence of the test methods according to our wish.
6) In addition to the above, TestNG allows parallel testing, which increases efficiency and improves the overall running time of test methods. With the TestNG framework, you can easily integrate with other tools such as Maven, Jenkins, etc. Moreover, TestNG provides a feature to run multiple test methods on various browsers to test for cross-browser compatibility issues on your website. It is cross-browser testing.
Additionally, TestNG allows us to run the tests separately. So, if you run the tests and only one test failed, you can run this test independently in the next execution.
Moreover, TestNG allows the test methods to depend on each other. It’s also called Test Dependency in TestNG.
Lastly, TestNG provides a bunch of assertion methods for testing more efficiently.
Subsequently, you can learn more about the benefits of the TestNG framework here.
Q79. How do you run the TestNG script?
TestNG script is run by right-click on the TestNG class -> Run As -> TestNG Test.
Q80. How to create and run TestNG.xml?
In TestNG framework, we need to create TestNG XML file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the XML file.
Q81. How can we create a data-driven framework using TestNG?
By using @DataProvider annotation, we can create a Data Driven Testing Framework.
@DataProvider(name=”getData”)
public Object[][] getData(){
//Object [][] data = new Object [rowCount][colCount];
Object [][] data = new Object [2][2];
data [0][0] = “FirstUid”;
data [0][1] = “FirstPWD”;
data[1][0] = “SecondUid”;
data[1][1] = “SecondPWD”;
return data;
}
Q82. What is Parameterized testing in TestNG?
Parameterized tests allow developers to run the same test over and over again using different values.
There are two ways to set these parameters:
with testng.xml –
<parameter name=“url” value=“https://www.guvi.in/”></parameter>
<parameter name=“username” value=“[email protected]”></parameter>
<parameter name=“password” value=“guvigeek”></parameter>
with Data Providers –
@DataProvider(name=”ReadExcel”)
public String[][] getData() throws IOException {
String[][] readData = ReadExcel.readExcelSheet(excelfile);
return readData;
}
@Test(dataProvider = “ReadExcel”)
Q83. How to set test case priority in TestNG?
We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical order.
package TestNG;
import org.testng.annotations.*;
public class PriorityTestCase{
@Test(priority=0)
public void testCase1() {
system.out.println(“Test Case 1”);
}
@Test(priority=1)
public void testCase2() {
system.out.println(“Test Case 2”);
}
}
Q84. What are the annotations available in TestNG?
@BeforeSuite : The annotated method will be run before all tests in this suite have run.
@BeforeTest : The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.
@BeforeClass : The annotated method will be run before the first test method in the current class is invoked.
@DataProvider : Marks a method as supplying data for a test method.
@BeforeMethod : The annotated method will be run before each test method.
@Test: Marks a class or a method as part of the test.
@AfterMethod: The annotated method will be run after each test method.
@AfterClass : The annotated method will be run after all the test methods in the current class have been run.
@AfterTest : The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.
@AfterSuite : The annotated method will be run after all tests in this suite have run.
@Parameters : To inject static datas into the testcase
@Parameters({“url”,”username”,”password”})
Q85. What is TestNG Assert and list out common TestNG Assertions?
TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any exception.
Some of the common assertions supported by TestNG are
- assertEqual(String actual,String expected)
- assertEqual(String actual,String expected, String message)
- assertEquals(boolean actual,boolean expected)
- assertTrue(condition)
- assertTrue(condition, message)
- assertFalse(condition)
- assertFalse(condition, message)
Q86. How to run test cases in parallel using TestNG?
We can use the “parallel” attribute in testng.xml to accomplish parallel test execution in TestNG
The parallel attribute of the suite tag can accept four values:
tests – All the test cases inside the <test> tag of testng.xml file will run parallel
classes – All the test cases inside a Java class will run parallel
methods – All the methods with @Test annotation will execute parallel
instances – Test cases in the same instance will execute in parallel but two methods of two different instances will run in different threads.
<suite name=”softwaretestingmaterial” parallel=”methods”>
Q87. How to disable a test case in TestNG?
To disable the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)
Q88. How to skip a @Test method from execution in TestNG?
By using throw new SkipException()
Once SkipException() thrown, remaining part of that test method will not be executed and control will goes directly to next test method execution.
throw new SkipException(“Skipping – This is not ready for testing “);
Q89. How to Ignore a test case in TestNG?
To ignore the test case we use the parameter enabled = false to the @Test annotation.
@Test(enabled = false)
Q90. How TestNG allows to state dependencies?
TestNG allows two ways to declare the dependencies.
Using attributes dependsOnMethods in @Test annotations.
Using attributes dependsOnGroups in @Test annotations.
Q91. What are the different ways to produce reports for TestNG results?
TestNG offers two ways to produce a report.
Listeners implement the interface org.testng.ITestListener and are notified in real-time of when a test starts, passes, fails, etc…
Reporters implement the interface org.testng.IReporter and are notified when all the suites have been run by TestNG. The IReporter instance receives a list of objects that describe the entire test run.
Q92. What is the use of @Listener annotation in TestNG?
TestNG listeners are used to configure reports and logging. One of the most widely used listeners in testNG is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We should implement this interface creating a listener class of our own. Next, we should add the listener’s annotation (@Listeners) in the Class which was created.
Q93. How to write regular expression In testng.xml file to search @Test methods containing “smoke” keyword.
Regular expression to find @Test methods containing keyword “smoke” is as mentioned below.
<methods>
<include name=”.*smoke.*”/>
</methods>
Q94. What is the time unit we specify in test suites and test cases?
We specify the time unit in test suites and test cases in milliseconds
Q95. List out various ways in which TestNG can be invoked.
TestNG can be invoked in the following ways
- Using Eclipse IDE
- Using the ant build tool
- From the command line
- Using IntelliJ’s IDEA
Q96. What is the use of @Test(invocationCount=x)?
The invocationcount attribute tells how many times TestNG should run a test method
@Test(invocationCount = 10)
public void testCase1(){
In this example, the method testCase1 will be invoked ten times
Q97. What is the use of @Test(threadPoolSize=x)?
The threadPoolSize attribute tells to form a thread pool to run the test method through multiple threads.
Note: This attribute is ignored if invocationCount is not specified
@Test(threadPoolSize = 3, invocationCount = 10) public void testCase1(){
In this example, the method testCase1 will be invoked from three different threads
Q98. What does the test timeout mean in TestNG?
The maximum number of milliseconds a test case should take.
@Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000)
public void testCase1(){
In this example, the function testCase1 will be invoked ten times from three different threads. Additionally, a time-out of ten seconds guarantees that none of the threads will block on this thread forever.
Q99. What are @Factory and @DataProvider annotations?
@Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective class with a different set of data.
@DataProvider: A test method that uses DataProvider will execute the specific methods multiple times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.
Q100. What is the Page Object Model in Selenium?
The Page Object Model is a Design Pattern that has become popular in Selenium Test Automation. It is a widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication.
Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword-driven, hybrid framework, etc.
A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page.
The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.
Q101. What is Page Factory?
We have seen that the ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.
Q102. What is the difference between a Page Object Model (POM) and a Page Factory?
Page Object is a class that represents a web page and holds the functionality and members. Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.
Q103. What are the advantages of the Page Object Model Framework?
Code reusability – We could achieve code reusability by writing the code once and using it in different tests.
Code maintainability – There is a clean separation between test code and page-specific code such as locators and layout which makes it very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.
Object Repository – Each page will be defined as a Java class. All the fields on the page will be defined in an interface as members. The class will then implement the interface.
Readability – Improves readability due to clean separation between test code and page-specific code
Q104. What are the OOPS Concepts applied in POM?
The 4 major OOPS Concepts in POM:
Abstraction
Abstraction is the methodology of hiding the implementation of internal details and showing the functionality to the users.
In the Page Object Model design pattern, we write locators (such as id, name, XPath, etc.,) and the methods in a Page Class. We utilize these locators in tests but we can’t see the implementation of the methods. Literally, we hide the implementations of the locators from the tests.
In Java, abstraction is achieved by interfaces and abstract classes. Using interfaces, we can achieve 100% abstraction.
Interface
The basic statement we all know in Selenium is WebDriver driver = new FirefoxDriver();
WebDriver itself is an Interface. So based on the above statement WebDriver driver = new FirefoxDriver(); we are initializing Firefox browser using Selenium WebDriver. It means we are creating a reference variable (driver) of the interface (WebDriver) and creating an Object. Here WebDriver is an Interface as mentioned earlier and FirefoxDriver is a class.
An interface in Java looks similar to a class but both the interface and class are two different concepts. An interface can have methods and variables just like the class but the methods declared in the interface are by default abstract. We can achieve 100% abstraction and multiple inheritance in Java with Interface.
Inheritance
The mechanism in Java by which one class acquires the properties (instance variables) and functionalities of another class is known as Inheritance. We create a Base Class in the Automation Framework to initialize the WebDriver interface, WebDriver waits, Property files, Excels, etc., in the Base Class.
We extend the Base Class to other classes such as Tests and Utility Class. Here we extend one class (Base Class like WebDriver Interface) into another class (like Tests, Utility Class) is known as Inheritance.
Polymorphism
Polymorphism allows us to perform a task in multiple ways. A combination of overloading and overriding is known as Polymorphism. We will see both overloading and overriding below.
1. Method Overloading
We use Implicit Wait in Selenium. The implicit wait is an example of overloading. In Implicit wait, we use different time stamps such as SECONDS, MINUTES, HOURS, etc.,
Action class in TestNG is also an example of overloading.
Assert class in TestNG is also an example of overloading.
A class having multiple methods with the same name but different parameters is called Method Overloading.
2. Method Overriding
We use a method that was already implemented in another class by changing its parameters. To understand this you need to understand Overriding in Java.
Declaring a method in a child class that is already present in the parent class is called Method Overriding. Examples are get and navigate methods of different drivers in Selenium.
Encapsulation
All the classes in a framework are an example of Encapsulation. In POM classes, we declare the data members using @FindBy and initialization of data members will be done using Constructor to utilize those in methods. Encapsulation is a mechanism of binding code and data (variables) together in a single unit.
You should have a deep understanding of Selenium if you want to get into this testing career, Selenium Automation Testing Course offered by GUVI would be the best course for you to begin with.
Conclusion
Now that you know about some of the most frequently asked and top Selenium Interview Questions and Answers, it’s time to get thorough with each of these questions. Start your preparation for getting a job as a manual tester. You should now focus on preparation tips for clearing tech interviews. These questions will definitely help you answer some of the tricky tech questions asked by interviewers. Kickstart your tech Selenium career now and get placed with a handsome salary package!
FAQs
What are the four parameters of Selenium?
There are four conditions (parameters) for Selenium to pass a test. These are as follows: URL, host, browser, and port number.
What are the 5 methods in Selenium?
There are five Selenium Method Categories in all:
1. Browser Methods
2. WebElement Methods
3. Navigation Methods
4. Wait Methods
5. Switch Methods
Is Selenium good for the future?
With a high demand for Selenium testers and lucrative salary packages altogether, it is a career that offers a promising future. Infycle Technologies is the right opportunity for you to learn in-depth training in software testing courses and their applications with the best Selenium course.
I really liked explanation of oops concepts with real time. This is how it has to be explained