Are you preparing for an interview for a Selenium automation testing Job in 2025? Whether you're just a beginner in Selenium or have 3 Years, 5 years, or 10 years of experience in automation testing, being well-prepared before an interview can make all the difference. Selenium is universally used and one of the most popular automation testing tools, and companies are always looking for skilled testers and developers who have a strong understanding of it.
To help you prepare, I have compiled a set of commonly asked Selenium interview questions and answers based on actual Selenium automation problems and industry best practices. I have automated several projects and have assisted teams in resolving real-world problems with Selenium automation. These are real answers drawn from real experience because I know what works and what does not in real life.
No matter what level of knowledge a person has, these questions seem to encapsulate everything from basic core understanding to advanced level framework building tasks done by a test automation engineer. Whether you are looking for a QA engineer position, test automation developer, or an SDET, this information will definitely help you in your next interview.
Basic Selenium Interview Questions
1. What is Selenium?
Selenium is a free automation testing tool that was initially developed by Jason Huggins. It is used to test web applications on different browsers and platforms. It is not only a browser automation tool, but you can automate your web-based repetitive tasks as well using Selenium.
You can use it to automate testing across several programming languages to develop test scripts. It also supports cross-browser and cross-platform testing using Selenium Grid. You can run Selenium tests on different browsers like Chrome, Firefox, Edge, Opera, and Safari to check browser compatibility. Also, you can run test scripts on different OS easily like Windows, Linux, and mac OS.
Unlike other automation tools, it interacts with browsers natively just like a real user. So it is easy to find UI level bugs as well.
2. What are the different components of Selenium?
- Selenium IDE – Shinya Kasatani developed it in 2006. Selenium IDE is an easy-to-use, open source browser extension that is used to record and play back test scripts.
- Selenium WebDriver – Selenium WebDriver is a very popular and powerful tool for programmatically automating browser interactions.
- Selenium Grid – Used for parallel execution of tests across multiple machines and browsers.
- Selenium RC (Deprecated) – The old version of Selenium WebDriver.
3. How does Selenium WebDriver work?
4. What are the advantages of using Selenium for automation testing?
- Cost Effective: It is open-source and free, which is the main advantage.
- Multi Language Support: No language specific dependency. It supports multiple programming languages.
- Platform Independent: No browser specific dependency. It supports multiple browsers.
- Saves Time: Selenium Grid allows for parallel test execution, which can save you significant time.
- Flexible & Easy Integration: Works with various testing frameworks (TestNG, JUnit, NUnit, Jenkins CI/CD, etc.)
- Active Community Support: Wide community support. Easy to find solutions online.
- Automate Tests as a Real User Do: It interacts with browsers directly. Same as a real user does.
- Create Framework As per Your Convenience: You can create different frameworks like data-driven, keyword-driven, Hybrid, etc, easily, as per your requirement.
5. What are the limitations of Selenium?
- Cannot automate desktop applications.
- Limited support to test mobile apps (needs Appium for that)
- No built-in reporting feature.
- Cannot handle captchas and OTPs directly
- It is challenging to handle pop-ups and dynamic web elements in Selenium.
6. What programming languages does Selenium support?
Selenium supports Java, Python, C#, Ruby, and JavaScript.
7. What types of applications can Selenium automate?
It can automate web applications only. You can test mobile apps with the help of Appium. You need third-party tools to automate desktop applications.
8. How do you set up Selenium WebDriver in a project?
9. What are the different locators in Selenium?
- ID – driver.findElement(By.id("username"))
- Name – driver.findElement(By.name("email"))
- Class Name – driver.findElement(By.className("login-btn"))
- Tag Name – driver.findElement(By.tagName("input"))
- Link Text – driver.findElement(By.linkText("Click Here"))
- Partial Link Text – driver.findElement(By.partialLinkText("Click"))
- CSS Selector – driver.findElement(By.cssSelector("#login"))
- XPath – driver.findElement(By.xpath("//input[@id='password']"))
10. What is the difference between findElement() and findElements()?
findElement() method will return a single Web Element (throws an error if element not found)
Example: WebElement element = driver.findElement(By.id("login")); // Returns a single element.
findElements() method is used to get a list of Web Elements (returns an empty list if element not found).
Example: List<WebElement> elements = driver.findElements(By.tagName("a")); // Returns a list of links
11. What is the difference between driver.get() and driver.navigate().to()?
driver.get("URL"): You can use it to load a new webpage and wait until it’s fully loaded.
Example: driver.get("https://example.com");
driver.navigate().to("URL") – It is similar to the get() method, but provides additional navigation features like back, forward, and refresh.
Example: driver.navigate().to("https://example.com");
12. How do you handle browser navigation in Selenium?
We can use the navigate() method for browser navigations.
To go back to the previous page, we can use driver.navigate().back();
We can use driver.navigate().forward(); to go forward.
This syntax is used to refresh the page: driver.navigate().refresh();
13. How do you handle different types of waits in Selenium?
1. Implicit Wait
Implicit wait is used to wait for elements globally.
Example of Implicit Wait: Given syntax will wait for 10 seconds while page is loading.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
2. Explicit WaitExplicit wait is used to wait for specific conditions.
Example of Explicit Wait: Given syntax will wait for 10 seconds for the element with the 'login' id to be visible.
3. Fluent Wait
14. What is the difference between implicit wait and explicit wait?
Implicit Wait
Explicit wait
15. What is a Fluent Wait in Selenium?
- The maximum amount of time to wait for a condition,
- The polling frequency.
- Ignoring specific exceptions while waiting.
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofSeconds(1))
.ignoring(NoSuchElementException.class);
16. How do you handle pop-ups and alerts in Selenium?
We can handle pop-ups and alerts using the Alert interface. We can use the accept() method to accept or click on the OK button, the dismiss() method to dismiss/cancel the alert. Also, it is possible to type text in the text field of alert using sendKeys() method.
Here is an example.
Alert alert = driver.switchTo().alert();
alert.accept(); // Click OK
alert.dismiss(); // Click Cancel
alert.sendKeys("Hello"); // Send text
17. How do you work with multiple browser windows in Selenium?
Example:
String mainWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
}
18. What is the difference between switchTo().window() and switchTo().frame()?
- switchTo().window("windowID"): It is used to switch between browser tabs/windows.
- switchTo().frame("frameID"): It is used to switch to an iframe on the page.
19. How do you handle dropdowns in Selenium?
We can use the Select class to handle alerts in Selenium. Here is an example on how to select dropdown options using visible text, value, and index.
Select dropdown = new Select(driver.findElement(By.id("dropdown")));
dropdown.selectByVisibleText("Option 1");
dropdown.selectByValue("option1");
dropdown.selectByIndex(0);
20. How do you select a value from a dropdown using Selenium?
- selectByVisibleText("Option")
- selectByValue("option1")
- selectByIndex(0)
Example:
Select dropdown = new Select(driver.findElement(By.id("dropdown")));
dropdown.selectByVisibleText("Java");
Selenium WebDriver Questions
21 What is WebDriver in Selenium?
Here are key features of WebDriver:
- It can directly communicate with the browser.
- It supports multiple browsers like Chrome, Firefox, Edge, Safari, etc.
- Works with multiple programming languages like Java, Python, C#, JavaScript, etc.
- You can easily use it on different OS like Windows, Linux, and Mac.
You can read this article to read more about WebDriver in Selenium.
22. How do you launch different browsers in Selenium WebDriver?
Here are the examples to launch different browsers in Selenium WebDriver test.
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebDriver driver = new FirefoxDriver();
driver.get("https://example.com");
WebDriver driver = new EdgeDriver();
driver.get("https://example.com");
WebDriver driver = new SafariDriver();
driver.get("https://example.com");
23. What is the difference between WebDriver and RemoteWebDriver?
On the other hand, RemoteWebDriver is a class that enables running Selenium tests on a remote machine. It communicates with the remote browser using the W3C WebDriver Protocol (previously JSON Wire Protocol in older Selenium versions). Generally, we use RemoteWebDriver to perform distributed testing, Selenium Grid, and cloud-based automation on platforms like BrowserStack and Sauce Labs.
Key Differences:
- Execution Location:
- WebDriver executes Selenium tests on the local machine.
- RemoteWebDriver runs tests remotely on another machine or cloud service.
- Communication Protocol:
- WebDriver directly interacts with the browser drivers.
- RemoteWebDriver executes Selenium commands using the W3C WebDriver Protocol over HTTP.
- Use Case:
- WebDriver is best for local automation on a single browser instance.
- You can use RemoteWebDriver to perform parallel execution across multiple machines in Selenium Grid or cloud testing services.
Example of WebDriver (Local Execution)
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Example of RemoteWebDriver (Remote Execution)
URL remoteUrl = new URL("http://192.168.1.100:4444"); // Selenium Grid URL
ChromeOptions options = new ChromeOptions(); // Use browser options instead of DesiredCapabilities
WebDriver driver = new RemoteWebDriver(remoteUrl, options);
driver.get("https://example.com");
24. How do you maximize a browser window in Selenium?
Example of Maximizing window using maximize_window() method
// Set up the WebDriver (Make sure ChromeDriver path is set in system properties)
WebDriver driver = new ChromeDriver();
// Open a website
driver.get("https://www.example.com");
// Maximize the browser window
driver.manage().window().maximize();
// Perform any test actions...
// Close the browser
driver.quit();
Here, driver.manage().window().maximize(); syntax will maximize the window.
WebDriver driver = new ChromeDriver();
driver.manage().window().setSize(new Dimension(1200, 800));
If your screen size is 1200 x 800, then you can use the .setSize() method to maximize the window.
Example of Maximizing window in Headless Browsers using addArguments("--start-maximized")
WebDriver driver;
FirefoxOptions options=new FirefoxOptions();
//To open browser in Headeless mode.
options.addArguments("--headless");
//To open headless browser maximized.
options.addArguments("--start-maximized");
driver = new FirefoxDriver(options);
The above example explains how to start a headless browser maximized.
Tips: You should run Selenium tests in a full-screen environment to prevent UI interaction issues.
25. How do you take a screenshot in Selenium WebDriver?
Example to take a Screenshot and Save as a File in Selenium
package com.secondpr; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class takeScreenShot { public static void main(String[] args) { // Set up WebDriver WebDriver driver = new ChromeDriver(); try { // Open a website driver.get("https://www.example.com"); // Take a screenshot TakesScreenshot ts = (TakesScreenshot) driver; File source = ts.getScreenshotAs(OutputType.FILE); // Define destination path File destination = new File("D:\\homePageScreenshot.png"); // Copy file to the destination FileUtils.copyFile(source, destination); System.out.println("Screenshot saved successfully!"); } catch (IOException e) { System.out.println("Error while saving screenshot: " + e.getMessage()); } finally { // Close the browser driver.quit(); } } }
26. How do you get the title of a webpage in Selenium?
Example to get webpage title:
// Get and print the title of the webpage String pageTitle = driver.getTitle(); System.out.println("Page Title: " + pageTitle);
27. How do you get the current URL of a webpage?
In Selenium WebDriver, you can use the getCurrentUrl() method to get the current URL of a webpage.
// Get and print the current URL String currentURL = driver.getCurrentUrl(); System.out.println("Current URL: " + currentURL);
28. How do you handle cookies in Selenium WebDriver?
An example to manage cookies
package com.secondpr; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.Cookie; import java.util.Set; public class manageCookies { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); // Open a website driver.get("https://only-testing-blog.blogspot.com/"); // 1. Get all cookies Set<Cookie> allCookies = driver.manage().getCookies(); System.out.println("All Cookies: " + allCookies); // 2. Get a specific cookie by name Cookie specificCookie = driver.manage().getCookieNamed("session_id"); System.out.println("Session Cookie: " + specificCookie); // 3. Add a new cookie Cookie newCookie = new Cookie("test_cookie", "123456"); driver.manage().addCookie(newCookie); System.out.println("Added new cookie: " + newCookie); // 4. Delete a specific cookie driver.manage().deleteCookieNamed("test_cookie"); System.out.println("Deleted 'test_cookie'"); // 5. Delete all cookies driver.manage().deleteAllCookies(); System.out.println("All cookies deleted"); // Close the browser driver.quit(); } }
Explanation of Cookie Handling Methods
- driver.manage().getCookies(); → Fetches all cookies.
- driver.manage().getCookieNamed("cookie_name"); → Retrieves a specific cookie by name.
- driver.manage().addCookie(new Cookie("name", "value")); → Adds a new cookie.
- driver.manage().deleteCookieNamed("cookie_name"); → Deletes a specific cookie.
- driver.manage().deleteAllCookies(); → Clears all cookies.
- To maintain user sessions without logging in repeatedly.
- Test authentication by manually adding session cookies.
29. How do you delete all cookies using Selenium?
30. What is the difference between close() and quit()?
- Functionality:
- close(): Closes the current browser window.
- quit(): Closes all browser windows opened by Selenium.
- Scope:
- close(): Only the active browser window is closed.
- quit(): All browser sessions initiated by WebDriver are closed.
- WebDriver Instance:
- close(): WebDriver session remains active if multiple windows exist.
- quit(): WebDriver session is terminated completely.
- Usage:
- close(): Used when handling multiple windows/tabs and only one needs to be closed.
- quit(): Used when the entire test execution is complete and no further actions are needed.
Best Practice: Always use quit() at the end of the test execution to avoid memory leaks!
31. How do you handle JavaScript alerts in Selenium?
- Simple Alert → Only has an "OK" button.
- Confirmation Alert → Has "OK" and "Cancel" buttons.
- Prompt Alert → Has a text box, along with "OK" and "Cancel" buttons.
Here is an explanation on how to manage alerts in Selenium.
Handling alerts is important for pop-ups, form validations, and confirmations in test automation.
32. How do you perform drag and drop in Selenium?
Here is an example of drag and drop
package com.secondpr;
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 dragDrop {
public static void main(String[] args) {
// Set up WebDriver
WebDriver driver = new ChromeDriver();
// Open a website with drag-and-drop functionality
driver.get("https://jqueryui.com/droppable/");
// Switch to iframe if the elements are inside one
driver.switchTo().frame(0);
// Locate source (element to be dragged) and target (element where to drop)
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Perform drag and drop
Actions actions = new Actions(driver);
actions.dragAndDrop(source, target).perform();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Drag and drop successful!");
// Close browser
driver.quit();
}
}
Other Ways to Perform Drag and Drop
Using clickAndHold(), moveToElement(), and release(). You can use this method when dragAndDrop() doesn’t work due to JavaScript interference.
Example:
Using moveByOffset() (Dragging to Specific Coordinates). You can use it when drop location is dynamic or doesn’t have a unique identifier.
Example:
- Use dragAndDrop(source, target).perform(); for standard cases.
- Use clickAndHold(), moveToElement(), and release() if dragAndDrop() doesn’t work.
- Use moveByOffset(x, y) for pixel-based movement.
- Always switch to the iframe first if elements are inside it.
33. How do you simulate keyboard and mouse actions in Selenium?
Using Actions Class (Recommended)
Mouse Actions Example
Actions actions = new Actions(driver);
actions.moveToElement(element).perform(); // Hover
actions.contextClick(element).perform(); // Right-click
actions.doubleClick(element).perform(); // Double-click
Keyboard Actions
actions.sendKeys(Keys.ENTER).perform(); // Press Enter
actions.keyDown(Keys.SHIFT).sendKeys("text").keyUp(Keys.SHIFT).perform(); // Type in uppercase
Using Robot Class (For Advanced Interactions)
Keyboard Input
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
Mouse Actions
robot.mouseMove(500, 300); // Move mouse
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); // Left-click
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Tips:
You can use the Actions class for web-based interactions, i.e. hover, right-click, drag & drop, keyboard inputs, and the Robot class for system-level interactions, i.e.. file uploads, screenshots, handling OS pop-ups. Actions class is preferred for browser-based automation, while Robot is used when Actions doesn't work.
34. What is the Actions class in Selenium?
The Actions class in Selenium performs advanced user interactions, such as mouse hover, right-click, double-click, drag-and-drop, and keyboard actions. It helps automate complex gestures that require a combination of keyboard and mouse events.
Its key features include mouse actions, keyboard inputs, and composite gestures for seamless automation.
35. What is the difference between Action and Actions class?
- Type:
- Action class: It is an Interface.
- Actions class: It is a Class.
- Purpose:
- Action class: It represents a single action.
- Actions class: It is used to build and perform a series of actions.
- Usage:
- Action class: It stores one action at a time.
- Actions class: It has a chain of multiple actions together.
// Using Actions class to build and perform actions
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform(); // Hover and click
// Using Action interface to store an action
Action action = actions.moveToElement(element).click().build();
action.perform(); // Perform stored action
36. How do you simulate right-click in Selenium?
Example:
WebElement element = driver.findElement(By.id("rightClickElement"));
Actions actions = new Actions(driver);
actions.contextClick(element).perform(); // Right-click action
37. How do you simulate double-click in Selenium?
You can perform a double-click in Selenium using the doubleClick() method from the Actions class.
Here is an example:
WebElement element = driver.findElement(By.id("doubleClickElement"));
Actions actions = new Actions(driver);
actions.doubleClick(element).perform(); // Double-click action
38. How do you handle frames and iframes in Selenium?
Here are examples using different methods:
Example of switch to frame by Index:
driver.switchTo().frame(0); // Switch to the first frame
driver.switchTo().frame("frameName"); // Switch using frame name or ID
WebElement frameElement = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame(frameElement); // Switch using WebElement
driver.switchTo().defaultContent(); // Exit from frame to main content
39. How do you work with checkboxes and radio buttons in Selenium?
Here is an example of Selecting a Checkbox and Radio Button.
WebElement checkbox = driver.findElement(By.id("subscribe"));
checkbox.click(); // Click to select
// Verify if checkbox is selected
if (checkbox.isSelected()) {
System.out.println("Checkbox is selected.");
}
WebElement radioButton = driver.findElement(By.id("genderMale"));
radioButton.click(); // Select radio button
40. How do you handle hidden elements in Selenium?
JavaScript Executor (Force Click)
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement hiddenElement = driver.findElement(By.id("hiddenButton"));
js.executeScript("arguments[0].click();", hiddenElement);
Checking Visibility Before Action
WebElement element = driver.findElement(By.id("hiddenElement"));
if (element.isDisplayed()) {
element.click();
} else {
System.out.println("Element is hidden");
}
Using Actions Class (For Hover to Reveal Elements)
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("menu"));
actions.moveToElement(menu).perform(); // Hover to make hidden element visible
Selenium Automation Framework Questions
41. What is a Selenium Framework?
Types of Selenium Frameworks:
Data-Driven Framework → Uses external data sources (Excel, CSV). You can use it to test multiple inputs without modifying scripts.
String data = excelSheet.getCellData("TestData.xlsx", "Sheet1", 1, 1);
executeAction("Click", "loginButton");
Hybrid Framework → Combines Data-Driven + Keyword-Driven approaches. It works well for large-scale automation projects.
Page Object Model (POM) → Organizes elements and actions into separate classes. It helps to improve code reusability & readability.
LoginPage login = new LoginPage(driver);
login.enterUsername("user");
login.clickLogin();
42. What are the different types of Selenium frameworks?
43. What is the Page Object Model (POM) in Selenium?
Key Advantages of POM:
- Helps to reduce duplicate code.
- Enhances test script readability.
- Easy to maintain test scripts when UI changes.
Create a Page Class (LoginPage.java)
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
public class LoginPage {
WebDriver driver;
// Locators
By username = By.id("user");
By password = By.id("pass");
By loginButton = By.id("login");
// Constructor
public LoginPage(WebDriver driver) {
this.driver = driver;
}
// Methods to interact with elements
public void enterUsername(String user) {
driver.findElement(username).sendKeys(user);
}
public void enterPassword(String pass) {
driver.findElement(password).sendKeys(pass);
}
public void clickLogin() {
driver.findElement(loginButton).click();
}
}
Use the Page Class in a Test (LoginTest.java)
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
LoginPage login = new LoginPage(driver);
login.enterUsername("testUser");
login.enterPassword("testPass");
login.clickLogin();
44. What are the advantages of using POM?
- Better Code Maintainability – You need to update only the page classes, If there is any change in the UI. Do not need to update all test cases.
- Increased Reusability – You can reuse common UI actions like login, search across multiple tests.
- Improved Readability – Test scripts are cleaner and easier to understand.
- Separation of Concerns – Keeps test logic separate from UI element locators.
- Reduces Code Duplication – No need to define locators in multiple places.
45. What is Page Factory in Selenium?
Key Benefits of Page Factory
- Automatic element initialization using @FindBy.
- Improves readability & maintainability of test scripts.
- Faster execution due to lazy loading of elements.
Example of Page Factory Implementation
Define Page Class (LoginPage.java)
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage {
WebDriver driver;
// Locate elements using @FindBy annotation
@FindBy(id = "user")
WebElement username;
@FindBy(id = "pass")
WebElement password;
@FindBy(id = "login")
WebElement loginButton;
// Constructor to initialize Page Factory
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
// Methods to interact with elements
public void enterUsername(String user) {
username.sendKeys(user);
}
public void enterPassword(String pass) {
password.sendKeys(pass);
}
public void clickLogin() {
loginButton.click();
}
}
Use Page Factory in Test (LoginTest.java)
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
LoginPage login = new LoginPage(driver);
login.enterUsername("testUser");
login.enterPassword("testPass");
login.clickLogin();
46. How is Page Factory different from POM?
- Element Initialization:
- POM: Uses driver.findElement() manually.
- Page Factory: Uses @FindBy annotation with PageFactory.initElements()
- Code Readability:
- POM: Requires more lines of code.
- Page Factory: Cleaner and more concise
- Performance:
- POM: Loads elements immediately.
- Page Factory: Uses lazy initialization, loading elements only when needed.
- Maintainability:
- POM: Requires explicit element declaration.
- Page Factory: Automatically initializes elements, making maintenance easier.
47. How do you handle dynamic elements in Selenium?
Using Dynamic XPath
WebElement element = driver.findElement(By.xpath("//*[contains(@id, 'dynamicPart')]"));
Using CSS Selectors with Wildcards
WebElement element = driver.findElement(By.cssSelector("[id^='start']"));
Using Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement")));
Using JavaScript Executor (If Element is Not Detected)
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('[id^=\"dynamic\"]');");
48. What is TestNG?
Key Features of TestNG:
- Annotations: We can use annotations like @Test, @BeforeMethod, @AfterMethod for structured testing.
- Parallel Test Execution: Allows to run multiple tests simultaneously.
- Assertions: Has great assertions for result validation.
- Report Generation: Can generate detailed test results.
49. What are the advantages of using TestNG?
Annotations for Better Test Structure → Uses @Test, @BeforeMethod, @AfterMethod for organized test execution.
Parallel Test Execution → Runs multiple tests at the same time, reducing execution time.
Built-in Reporting → Generates detailed HTML test reports automatically.
Data-Driven Testing with @DataProvider → Enables testing with multiple data sets.
Flexible Test Execution with XML → Run specific tests by modifying the testng.xml file.
Example:
@DataProvider(name = "loginData")
public Object[][] getData() { return new Object[][] { {"user1", "pass1"}, {"user2", "pass2"} }; }
50. What is the difference between JUnit and TestNG?
JUnit
- Annotations: You can use @Test, @Before, @After annotations.
- Dependency Support: No built-in support for test dependencies
- Parallel Execution: Not supported.
- Parameterized Tests: Uses @RunWith(Parameterized.class).
- Reporting: Basic reporting.
- Test Execution Control: Runs tests alphabetically.
TestNG
- Annotations: More powerful annotations that include @BeforeMethod, @AfterMethod. @DataProvider
- Dependency Support: Supports dependencies using dependsOnMethods.
- Parallel Execution: Supported using testng.xml.
- Parameterized Tests: Uses @DataProvider (more flexible).
- Reporting: Generates detailed HTML reports.
- Test Execution Control: Runs based on priority using priority attribute.
51. What is an annotation in TestNG?
Here is the list of common TestNG annotations with their usage.
- @Test: Marks a method as a test case.
- @BeforeMethod: Runs before each test method.
- @AfterMethod: Runs after each test method.
- @BeforeClass: Runs once before all test methods in a class.
- @AfterClass: Runs once after all test methods in a class.
- @DataProvider: Provides test data for data-driven testing.
- @Parameters: Passes values from testng.xml to test cases.
52. What is a DataProvider in TestNG?
Here are key features:
- You can use it to run the same test with multiple inputs.
- Eliminates hardcoded test data in test scripts.
- Can fetch data from Excel, CSV, or databases.
53. How do you use DataProvider to pass test data?
- Define a method with @DataProvider.
- Return a 2D Object array containing test data.
- Use @Test(dataProvider = "providerName") to link the test with the DataProvider.
Example: Passing Test Data Using DataProvider
import org.testng.annotations.*;
public class DataProviderExample {
// Step 1: Define DataProvider
@DataProvider(name = "loginData")
public Object[][] getData() {
return new Object[][] {
{"user1", "pass1"},
{"user2", "pass2"},
{"user3", "pass3"}
};
}
// Step 2: Use DataProvider in Test
@Test(dataProvider = "loginData")
public void testLogin(String username, String password) {
System.out.println("Testing login with: " + username + " / " + password);
// Add Selenium code to perform login here
}
}
54. What is a TestNG XML file?
- To run multiple test classes together.
- To group and prioritize test cases.
- Parallel test execution.
- To pass parameters to test methods.
Example: Basic TestNG XML File (testng.xml)
<suite name="TestSuite">
<test name="LoginTest">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite>
How to Run Tests Using TestNG XML?
- Right click on the testng.xml file.
- Select "Run As → TestNG Suite" in Eclipse.
55. How do you run tests in parallel using TestNG?
Steps to Run Tests in Parallel:
- Set parallel="methods" or parallel="classes" in testng.xml.
- Define thread-count to control how many threads run at the same time.
Example: Parallel Execution of Test Methods (testng.xml)
<suite name="ParallelSuite" parallel="methods" thread-count="2">
<test name="ParallelTest">
<classes>
<class name="tests.ParallelTest"/>
</classes>
</test>
</suite>
Java Example: Parallel Test Execution
import org.testng.annotations.Test;
public class ParallelTest {
@Test
public void testOne() {
System.out.println("Test One - " + Thread.currentThread().getId());
}
@Test
public void testTwo() {
System.out.println("Test Two - " + Thread.currentThread().getId());
}
}
56. What is the difference between soft assert and hard assert?
Hard Assert:
- Stops Execution?: Yes, it stops execution once test fails and so assertion fails.
- Multiple Assertions?: Not possible, as execution stops on failure.
- Best For?: Critical validations like login success.
Soft Assert:
- Stops Execution?: Execution will continue even if assertion fails.
- Multiple Assertions?: Possible, as failures are collected and reported at the end.
- Best For?: Non-critical checks (e.g., UI element verification).
57. How do you generate reports in TestNG?
Default TestNG Report (HTML & XML)
- TestNG creates a report in the test-output folder once you run the test.
- You can open test-output/index.html file in a browser to view the report.
Generating Custom Reports Using IReporter
You can implement IReporter to customize reports as below.
import org.testng.IReporter;
import org.testng.ISuite;
import org.testng.xml.XmlSuite;
import java.util.List;
public class CustomReport implements IReporter {
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
System.out.println("Generating custom report...");
}
}
Add to testng.xml:
<listeners>
<listener class-name="reports.CustomReport"/>
</listeners>
Using ITestListener for Custom Logs
Capture test start, success, and failure logs.
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener {
public void onTestSuccess(ITestResult result) {
System.out.println("Test Passed: " + result.getName());
}
public void onTestFailure(ITestResult result) {
System.out.println("Test Failed: " + result.getName());
}
}
Add to testng.xml:
<listeners>
<listener class-name="listeners.TestListener"/>
</listeners>
58. What is Maven and how does it help in Selenium automation?
How Maven Helps in Selenium Automation?
- Manages Dependencies Automatically: No need to download JAR files manually.
- Standard Project Structure: It follows a predefined structure. So it is easy to maintain a project.
- Easier Test Execution: You can run tests using a simple command "mvn test".
- Integration with CI/CD: You can integrate it easily with Jenkins, GitHub Actions, Azure DevOps for automation.
- Parallel & Cross-Browser Testing: It is easy to configure TestNG for parallel execution using Maven.
59. What is a pom.xml file in Maven?
- Project details (name, version, description).
- Dependencies (e.g., Selenium, TestNG).
- Plugins (e.g., Maven Surefire for running tests).
- Build and execution commands.
How pom.xml Helps in Selenium?
- Manages dependencies automatically: No need to download JARs manually.
- Easy test execution: Run tests using mvn test.
- Integrates with CI/CD: Works with Jenkins, GitHub Actions, etc.
60. How do you integrate Selenium with Maven?
Steps to Integrate Selenium with Maven
In Eclipse/IntelliJ: File → New → Maven Project → Select Quickstart Archetype.
Add Selenium & TestNG Dependencies in pom.xml
<dependencies> <!-- Selenium WebDriver --> <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.29.0</version> </dependency> <!-- TestNG --> <!-- https://mvnrepository.com/artifact/org.testng/testng --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.11.0</version> <scope>test</scope> </dependency> </dependencies>
Write a Sample Selenium Test (Java)
Create a test class in src/test/java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class GoogleTest {
@Test
public void openGoogle() {
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
System.out.println("Title: " + driver.getTitle());
driver.quit();
}
}
Run Tests Using Maven
mvn test
General Tips From Experts for Answering Interview Questions
- Understand the Question – Ensure that you take a moment before answering the question and ask for clarification if needed.
- Match Answers to the Company’s Needs: Research about the company and personalize your responses accordingly.
- Stay Positive & Professional: Avoid insulting past employers and use challenges as a learning experience.
- Here are a few expert tips from the Muse article
- Use the STAR Method – For more clarity, organize your responses using Situation, Task, Action, and Result.
- Be Concise and Relevant – Try to keep your answers under 2 minutes and avoid going into unnecessary detail.
- Highlight Results & Impact: You can showcase your impacts using numbers and metrics, which makes your achievements clear, memorable, and results-driven.
- Practice, But Don’t Memorize: Practice answering common questions while keeping the responses natural.
No comments:
Post a Comment