Top Java Selenium Interview Questions & Answers
1. What is Java?
Java is a high-level, object-oriented, platform-independent programming language used for developing web, desktop, mobile, and automation applications.
2. What are the features of Java?
- Platform independent
- Object-oriented
- Secure
- Robust
- Multithreaded
- Portable
3. What are variables in Java?
Variables are containers used to store data values.
Example:
int age = 25;
4. What are data types in Java?
Two types:
- Primitive → int, char, boolean
- Non-primitive → String, Array, Class
5. What is the difference between primitive and non-primitive data types?
| Primitive | Non-Primitive |
| Stores value | Stores reference |
| Fixed size | Dynamic size |
6. What is type casting in Java?
Converting one datatype into another datatype.
Example:
double d = 10.5;
int i = (int)d;
7. What are operators in Java?
Operators perform operations on variables.
Examples:
- Arithmetic (+)
- Logical (&&)
- Relational (>)
8. What is the difference between == and .equals()?
| == | .equals() |
| Compares memory reference | Compares values |
9. What are OOPs concepts in Java?
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
10. What is encapsulation?
Encapsulation means wrapping data and methods together in a single class and restricting direct access using private variables.
11. What is inheritance?
Inheritance allows one class to acquire properties and methods of another class using extends keyword.
12. What is polymorphism?
Polymorphism means one method can perform different actions based on the object.
Types:
- Overloading
- Overriding
13. What is abstraction?
Abstraction means hiding implementation details and showing only required functionality.
14. What is the difference between abstraction and encapsulation?
| Abstraction | Encapsulation |
| Hides implementation | Hides data |
15. What is method overloading?
Method overloading means creating multiple methods with same name but different parameters.
16. What is method overriding?
Method overriding means redefining parent class method in child class with same signature.
17. What is the difference between overloading and overriding?
| Overloading | Overriding |
| Same class | Parent-child class |
| Different parameters | Same parameters |
| Compile-time polymorphism | Runtime polymorphism |
18. What is an interface in Java?
An interface is a blueprint containing abstract methods that must be implemented by classes.
19. What is an abstract class?
An abstract class is a class declared using abstract keyword. It can contain abstract and non-abstract methods
20. What is the difference between interface and abstract class?
| Interface | Abstract Class |
| Supports multiple inheritance | Partial abstraction |
| Mostly abstract methods | Can contain concrete methods |
21. What is constructor in Java?
Constructor initializes object.
22. What is constructor overloading?
A constructor is a special method used to initialize objects.
23. What is constructor overloading?
Creating multiple constructors with different parameters is called constructor overloading
23. What is the difference between a constructor and a method?
| Constructor | Method |
| Initializes object | Performs operations |
| Same name as class | Any valid name |
24. What is this keyword?
Refers to current class object.
25. What is super keyword?
super refers to parent class object or constructor.
26. What is static keyword in Java?
static belongs to class instead of object.
27. What is final keyword in Java?
Used to:
- Prevent inheritance
- Prevent overriding
- Declare constants
28. Can we override static or final methods?
No, static and final methods cannot be overridden.
29. What is String in Java?
String is a sequence of characters used to store text.
30. What is the difference between String, StringBuffer, and StringBuilder?
| String | StringBuffer | StringBuilder |
| Immutable | Mutable | Mutable |
| Slow | Thread-safe | Faster |
31. Why is String immutable in Java?
For security, thread safety, and performance.
32. What is string pooling?
Java stores string literals in common memory called String Pool.
33. What is the difference between equals() and equalsIgnoreCase()?
| equals() | equalsIgnoreCase() |
| Case-sensitive | Ignores case |
34. How do you reverse a string in Java?
Using StringBuilder:
String rev = new StringBuilder(str).reverse().toString();
35. How do you remove duplicates from a string?
Duplicates can be removed using loops, Set collection, or HashSet.
36. How do you count characters in a string?
Using length() method.
str.length();
37. What is an array in Java?
An array is a collection of elements of the same datatype stored in a single variable. It is used to store multiple values together using index positions.
38. What is ArrayList?
ArrayList is a class in Java Collection Framework used to store dynamic collections of elements. Unlike arrays, its size can grow or shrink automatically.
39. What is the difference between Array and ArrayList?
| Array | ArrayList |
| Fixed size | Dynamic size |
| Stores primitives | Stores objects |
40. What is the difference between List, Set, and Map?
41. What is HashMap in Java?
Stores key-value pairs
42. What is the difference between HashMap and Hashtable?
| HashMap | Hashtable |
| Not synchronized | Synchronized |
43. What is the difference between HashSet and TreeSet?
| HashSet | TreeSet |
| Unordered | Sorted |
44. What is an Iterator in Java?
Used to traverse collection elements.
45. What is the difference between Iterator and ListIterator?
| Iterator | ListIterator |
| Forward only | Forward & backward |
46. What is the Collection Framework in Java?
Framework containing classes/interfaces for storing data.
47. What is Comparable and Comparator?
| Comparable | Comparator |
| Natural sorting | Custom sorting |
48. What is the difference between ArrayList and LinkedList?
| ArrayList | LinkedList |
| Faster retrieval | Faster insertion/deletion |
49. What is exception handling in Java?
Mechanism to handle runtime errors.
50. What is the difference between checked and unchecked exceptions?
| Checked | Unchecked |
| Compile-time | Runtime |
51. What is a try-catch block?
Used to handle exceptions.
52. What is a finally block?
Always executes whether exception occurs or not.
53. What is throw and throws keywords?
| throw | throws |
| Throws exception | Declares exception |
54. Can a finally block execute without a catch block?
Yes.
55. What is NullPointerException?
Occurs when accessing a null object.
56. What is exception propagation?
Passing an exception from one method to another.
57. What is file handling in Java?
Reading and writing files using Java classes.
58. How do you read data from a file in Java?
Using:
- BufferedReader
- Scanner
- FileReader
59. How do you write data into a file?
Using FileWriter or BufferedWriter.
60. What is BufferedReader?
Used to read text efficiently.
61. What are FileInputStream and FileOutputStream?
Used to read/write byte data.
62. What is multithreading in Java?
Executing multiple threads simultaneously.
63. What is a thread in Java?
Smallest unit of execution.
64. What is the difference between process and thread?
| Process | Thread |
| Independent execution | Part of process |
65. How do you create a thread in Java?
Using:
- Thread class
- Runnable interface
66. What is synchronization?
Prevents multiple threads from accessing shared resources simultaneously.
67. What is thread sleep?
Pauses thread execution temporarily.
68. What are Locators in Selenium?
Locators are used to identify web elements on a webpage so that Selenium can interact with them.
- id
- name
- className
- tagName
- linkText
- partialLinkText
- xpath
- cssSelector
69. What is XPath, and what are the types of XPath?
XPath is a locator strategy used to navigate through XML/HTML DOM structure.
Types:
- Absolute XPath → starts from root (
/html/body/...) ❌ not recommended - Relative XPath → flexible and stable (
//input[@id='email']) ✅
XPath is useful for:
- Dynamic elements
- Complex structures
70. What is a page object model?
The Page Object Model (POM) is a design pattern used in test automation that helps you create clean, maintainable, and reusable test code — especially for web applications.
In POM, each web page of your application is represented by a separate class (a “Page Object”), and all the elements (buttons, fields, links, etc.) and actions (clicks, form submissions, etc.) on that page are defined as methods in that class.
Better Code Organization
Keeps UI locators and actions in one place.
Reusability
You can use the same page object in multiple tests.
Easier Maintenance
If a page changes, you update only one file — not all your test scripts.
Improved Readability
Tests become more readable and behave like real-world actions.
71. What is the role of TestNG in Automation Testing?
TestNG is a testing framework that helps organize, execute, and manage automated tests efficiently. It supports features like test grouping, prioritization, parallel execution, and data-driven testing.
It also generates detailed reports and integrates well with tools like Selenium and CI/CD pipelines
72. What are Waits in Selenium?
Waits are used to handle synchronization issues when elements take time to load. Without waits, Selenium may try to interact with elements before they are available, causing failures.
Types:
- Implicit Wait → applies globally
- Explicit Wait → waits for specific condition
- Fluent Wait → customizable
Best practice:
Use Explicit Wait for better control.
73. Difference between Implicit and Explicit Wait
Implicit wait is applied globally and waits for all elements, whereas explicit wait is applied to specific elements based on conditions.
Example:
- Wait until element is clickable
- Wait until element is visible
Explicit wait is preferred because it is more efficient and avoids unnecessary delays.
74. How do you handle dropdowns?
Dropdowns are handled using the Select class in Selenium when the HTML uses <select> tag.
We can select options using:
- Visible text
- Value
- Index
For custom dropdowns (non-select):
We use click and XPath.
75. How do you handle alerts?
Alerts are popups that require user action. Selenium handles them using switchTo().alert().
Operations:
- accept() → click OK
- dismiss() → click Cancel
- getText() → read message
Important:
You must switch to alert before interacting with it.
76. What is StaleElementException?
This exception occurs when the element is no longer attached to the DOM. It usually happens when
- Page refreshes
- DOM updates dynamically
Solution:
- Re-locate the element
- Use explicit wait
77. What is Actions class?
Actions class is used to perform advanced user interactions that cannot be done using simple commands
Examples:
- Mouse hover
- Drag and drop
- Right-click
Used in complex UI scenarios.
78. What is JavaScriptExecutor?
JavaScriptExecutor allows executing JavaScript code inside the browser.
Used when:
- Selenium cannot click element
- Need to scroll page
- Handle hidden elements
Example:
js.executeScript(“window.scrollBy(0,500)”);
79. What is Data-Driven Testing?
In this approach, test data is stored externally (Excel, CSV, JSON), and tests are executed using different data sets.
Benefits:
- Reusability
- Multiple test scenarios
- Better coverage
80. How do you handle failures in automation?
Failures are handled using:
- Retry mechanism
- Screenshot capture
- Logging (Log4j)
- Reports (Extent Reports)
81. What are the different types of navigation commands?
Navigation commands are used to move between pages.
Methods:
- get() → open URL
- navigate().to() → go to URL
- navigate().back() → go back
- navigate().forward() → go forward
- navigate().refresh() → refresh page
82. What is the difference between findElement and findElements?
- findElement → returns a single element, throws exception if not found
- findElements → returns a list of elements, returns empty list if not found
83. How do you handle frames in Selenium?
Frames are handled using switchTo().frame().
Types:
- By index
- By name/id
- By WebElement
84. What is Page Factory in Selenium?
Page Factory is an extension of POM that uses @FindBy annotation to initialize elements.
85. What is Fluent Wait?
Fluent Wait is an advanced wait with customizable timeout and polling interval.
Features:
- Ignore specific exceptions
- Set polling frequency
86. What are common exceptions in Selenium?
Examples:
- NoSuchElementException
- TimeoutException
- StaleElementReferenceException
- ElementNotInteractableException
87. How do you capture screenshots in Selenium?
Using TakesScreenshot interface.
Used for:
- Failure analysis
- Reporting
88. How do you scroll a webpage in Selenium?
Using JavaScriptExecutor.
Examples:
- scrollBy()
- scrollIntoView()
89. How do you handle multiple windows/tabs?
Use getWindowHandles() and switchTo().window()
Steps:
- Store window IDs
- Switch between them
90. How do you implement retry logic in Selenium?
Using TestNG RetryAnalyzer or custom logic to rerun failed tests.
91. How do you design a scalable automation framework?
Use:
- Page Object Model
- Reusable utilities
- Data-driven approach
- Proper logging & reporting
92. What is the difference between Hard Assert and Soft Assert?
- Hard Assert → stops execution on failure
- Soft Assert → continues execution and reports all failures at end
93. How do you integrate Selenium with CI/CD?
Using tools like:
- Jenkins
- GitHub Actions
Steps:
- Trigger tests on build
- Run tests automatically
- Generate reports
94. What is logging in Selenium?
Logging helps track test execution.
Tools:
- Log4j
- SLF4J
95. How do you parameterize tests in TestNG?
Using:
- @DataProvider
- @Test parameters
96. What are best practices in Selenium automation?
- Use stable locators
- Avoid Thread.sleep
- Use Page Object Model (POM)
- Keep tests independent
- Maintain reusable code
97.What is broken link?
A broken link is a hyperlink that does not work or leads to an error page (like 404 Not Found), usually because the target page is missing or invalid.
98. What is the difference between driver.close() and driver.quit()?
- driver.close() → closes current browser window
- driver.quit() → closes all browser windows and ends session
99. What is getText() vs getAttribute()?
- getText() → gets visible text
- getAttribute() → gets attribute value (like value, href)
100. What is a WebElement?
WebElement represents an HTML element in Selenium.
Used to perform actions like:
- click()
- sendKeys()
- getText()
101. What is Maven in Selenium?
Maven is a build automation tool.
Used for:
- Managing dependencies
- Running tests
- Project structure
102. What is Jenkins in Selenium?
Jenkins is a CI/CD tool used to automate test execution.
Used for:
- Scheduling test runs
- Integrating with Git
- Generating reports
103. How do you check if an element is displayed on the page?
Methods:
- isDisplayed()
- isEnabled()
- isSelected()
Used for validation in test cases
104. What is the difference between click() and submit()?
- click(): Clicks any element
- submit(): submit a form
105. How do you handle disabled elements?
Selenium cannot interact directly.
Solution:
- Use JavaScriptExecutor
- Remove disabled attribute
106. What is the difference between getWindowHandle() and getWindowHandles()?
- getWindowHandle(): Returns single window ID
- getWindowHandles(): Returns all window IDs
107. How do you handle dynamic tables?
Steps:
- Locate table
- Use loops for rows and columns
- Use dynamic XPath
108. What is the best wait strategy in Selenium?
Best practice:
- Use Explicit Wait
- Avoid mixing waits
- Avoid Thread.sleep()
109. How do you ensure your automation is stable?
Best practices:
- Use stable locators
- Use waits properly
- Keep tests independent
110 .How do you handle auto-suggestions (like Google search)?
Steps:
- Enter text
- Capture suggestions
- Loop and select
111. What is DOM in Selenium?
DOM (Document Object Model) represents the structure of a webpage.
Used for:
- Locating elements
- Understanding hierarchy
112. How do you handle dynamic elements in Selenium?
Dynamic elements change attributes like id or class at runtime.
Solution:
- Use relative XPath
- Use functions like: contains() ,starts-with()
- Use stable attributes
Example:
//input[contains(@id,’user’)]
113. What will you do if your script fails randomly?
This is called flaky tests.
Approach:
- Add proper waits (Explicit Wait)
- Check synchronization issues
- Verify locators
- Add logging and screenshots
114. How do you handle file upload in Selenium?
If input type=”file”:
Use sendKeys() with file path
If custom upload:
Use AutoIT or Robot class
115. How do you handle file download?
Selenium cannot directly handle OS-level downloads.
Solution:
- Set browser download preferences
- Verify file in download folder
116. How do you validate broken links?
Steps:
- Get all links using findElements(By.tagName(“a”))
- Use HTTP connection
- Check response code
Codes:
- 200 → OK
- 404 → Broken
117. How do you scroll to a specific element?
Using JavaScriptExecutor:
scrollIntoView()
118. How do you handle shadow DOM elements?
Shadow DOM elements are hidden inside shadow root.
Solution:
- Use JavaScriptExecutor
- Access shadowRoot
119. What is the difference between driver.get() and driver.navigate().to()?
get():
- Waits for page load
- Used for initial load
navigate().to():
- Similar but used for navigation
120. How do you run tests in parallel in Selenium?
Using TestNG:
- parallel=”methods” or “classes” in XML
- Use Selenium Grid
121. How do you manage test data?
Using:
- Excel (Apache POI)
- JSON
- DataProvider in TestNG
122. How do you handle stale element exceptions in real projects?
Solution:
- Re-locate element
- Use Explicit Wait
- Avoid storing WebElement for long
123. What challenges did you face in automation?
- Dynamic elements
- Synchronization issues
- Browser compatibility
- Slow execution
124. How do you identify if an element is not clickable?
Check:
- Visibility
- Enabled state
- Overlapping elements
Use:
Explicit Wait → elementToBeClickable
125. How do you debug a failed test case?
Steps:
- Check logs
- Check screenshots
- Re-run test
- Validate locators
- Check environment
126. How do you handle cookies in Selenium?
Methods:
- addCookie()
- getCookies()
- deleteCookie()
127. How do you integrate your framework with CI/CD?
Steps:
- Push code to Git
- Configure Jenkins job
- Trigger build
- Run tests
- Generate report
128. How do you capture screenshots only on failure?
Using:
- TestNG listeners (ITestListener)
- Take screenshot in onTestFailure()
129. What is the difference between Absolute and Relative path?
Absolute:
- Full path
- Not stable
Relative:
- Flexible
- Recommended
130. Your test works in Chrome but fails in Firefox. What will you do?
Possible reasons:
- Different browser behavior
- Locator compatibility issues
- Timing issues
Solution:
- Use cross-browser compatible locators
- Add explicit waits
- Use browser-specific options if needed
131. Element is visible but Selenium is unable to click it. Why?
Possible causes:
- Element overlapped by another element
- Element not clickable yet
- Hidden behind loader
Solution:
- Use Explicit Wait → elementToBeClickable
- Scroll into view
- Use JavaScriptExecutor click as fallback
132. Your XPath is correct but still element is not found. What could be wrong?
Reasons:
- Element inside iframe
- Element inside shadow DOM
- Page not fully loaded
Solution:
- Switch to frame
- Handle shadow root
- Use wait
133. How do you automate a page where elements load after scrolling?
Solution:
- Use JavaScriptExecutor to scroll
- Load elements dynamically
- Use loop until element appears
134. How do you handle a situation where element ID changes every time?
Solution:
- Use contains() or starts-with()
- Use parent-child XPath
- Use other stable attributes
135. Your test passes locally but fails in Jenkins. Why?
Common reasons:
- Environment difference
- Headless mode issues
- Timing issues
Solution:
- Add proper waits
- Check environment configs
- Add logging
136. How do you design your framework for multiple users/logins?
Solution:
- Use DataProvider
- Store test data externally
- Parameterize login
137. How do you handle a calendar/date picker?
Types:
- Simple → sendKeys()
- Complex → click through UI
Steps:
- Open calendar
- Navigate month/year
- Select date
138. How do you handle pagination (multiple pages)?
Solution:
- Loop through pages
- Click “Next” button
- Extract data until last page
139. How do you verify if a file is successfully downloaded?
Steps:
- Set download directory
- Check file existence
- Validate file name
140. What will you do if execution is very slow?
Optimization:
- Run tests in parallel
- Remove Thread.sleep()
- Use headless mode
- Optimize locators
141. How do you handle dependency between test cases?
Solution:
- Avoid dependency (best practice)
- Use TestNG dependsOnMethods if needed
142. How do you test a login page with multiple invalid inputs?
Approach:
- Use DataProvider
- Pass multiple datasets
Example:
- Invalid username
- Invalid password
- Empty fields
143. What if application UI changes frequently?
Solution:
- Use POM design
- Centralize locators
- Use stable attributes
144. How do you validate error messages?
Steps:
- Capture element text
- Compare with expected
Use:
assertEquals()
145. What are the test types supported by Selenium?
For testing web-based applications, Selenium can be used.
The test types supported by Selenium are:
- Functional testing: It verifies if each function of a software application performs in accordance with specific requirements. This testing primarily involves black-box testing, and it is not concerned with the source code of the application.
- Regression testing: It is nothing but a full or partial selection of the already executed test cases to be re-executed to ensure that the existing functionalities work fine.
146. In Selenium, what are breakpoints and start points?
Breakpoints: Breakpoints are used to stall the execution of the test. The execution will stop whenever a breakpoint is implemented, and this will help us check whether the code is working properly or not.
Start points: Start points are the points from where the execution should begin. Start points can be used when we want to run the test script from the middle of the code or after a breakpoint.
147. What is DOM inspection?
Inspecting webpage structure using browser DevTools.
Used for:
- Locators
- XPath
- CSS selectors
148. What are the latest features in Selenium 4?
Features:
- Relative locators
- Selenium Manager
- Improved Grid
- Better DevTools support
- New window/tab handling
149. What is smoke suite in automation?
Small set of critical test cases executed after every build.
Purpose:
- Verify build stability quickly.
150. What is a locator strategy hierarchy?
Preferred locator order:
- ID
- Name
- CSS Selector
- XPath
Because IDs are fastest and most stable.
151. What are flaky tests?
Tests that:
- Pass sometimes
- Fail sometimes
Reasons:
- Timing issues
- Dynamic elements
- Environment instability
152. How do you reduce flaky tests?
- Use explicit waits
- Stable locators
- Retry mechanism
- Proper synchronization
- Independent tests
153. What metrics do you track in automation?
- Pass/fail percentage
- Automation coverage
- Execution time
- Defect leakage
- Stability rate
154. What reporting tools are used with Selenium?
Popular reporting tools:
- Extent Reports
- Allure Reports
- TestNG Reports
155. What is Extent Report?
Advanced HTML reporting library used for:
- Logs
- Screenshots
- Execution reports
156. What is the difference between verification and validation?
| Verification | Validation |
| Checks whether product is built correctly | Checks whether correct product is built |
| Process-oriented | Product-oriented |
157. What is ThreadLocal in Selenium?
Used in parallel execution to maintain separate WebDriver instances per thread.
Example use:
- Parallel test execution in TestNG
158. How do you automate OTP-based login?
Usually OTP is not automated directly.
Approaches:
- Disable OTP in test environment
- Fetch OTP from database/API/email
- Use static OTP in lower environments
159. What if developer changes locator frequently?
- Use relative XPath/CSS
- Coordinate with developers
- Add stable attributes like data-testid
160. How do you validate large datasets in UI?
- Database comparison
- API validation
- Dynamic table handling
161. What if test data is unavailable?
Approaches:
- Generate test data dynamically
- Use APIs/database
- Mock services
162. How do you manage secrets/passwords in framework?
Never hardcode credentials.
Use:
- Environment variables
- Vault tools
- Encrypted config
163. How do you validate images on webpage?
Check:
- Image displayed
- HTTP response
- Natural width > 0
164. How do you handle hidden elements?
Using:
- JavaScriptExecutor
- Actions class
- Wait until visible
165.What will you do if there are no unique locators?
Use:
- Relative XPath
- Parent-child relationship
- CSS hierarchy
- Multiple attributes
166. What is a Keyword-Driven Framework?
A Keyword-Driven Framework is an automation framework where test actions are represented using predefined keywords like Click, Type, and Login.
The test data, locators, and actions are maintained separately from the test scripts, making the framework more reusable, maintainable, and easy to understand.
167. What is TestNG?
TestNG (Test Next Generation) is a testing framework inspired by JUnit and NUnit but designed to be more powerful and flexible. It supports annotations, parallel execution, data-driven testing, and reporting.
168. What are the main features of TestNG?
TestNG (Test Next Generation) is a testing framework inspired by JUnit and NUnit but designed to be more powerful and flexible. It supports annotations, parallel execution, data-driven testing, and reporting.
- Annotation-based testing
- Parallel test execution
- Data-driven testing using DataProvider
- Flexible test configuration
- Dependency management
- Detailed reporting
169. What are TestNG annotations?
Annotations define how methods should behave in a test. Common ones include:
- @Test – marks a test method
- @BeforeMethod / @AfterMethod
- @BeforeClass / @AfterClass
- @BeforeSuite / @AfterSuite
170. What is the difference between @BeforeMethod and @BeforeClass?
- @BeforeMethod: runs before each test method
- @BeforeClass: runs once before all test methods in a class
171. What is the difference between TestNG and JUnit?
| TestNG | JUnit |
| Supports parallel execution | Limited parallel support |
| Supports dependency testing | No dependency feature |
| Supports DataProvider | Limited parameterization |
| More flexible annotations | Fewer annotations |
| Better reporting | Basic reporting |
172. What is testng.xml file?
testng.xml is a configuration file used to control test execution in TestNG.
It helps to:
- Define test suites
- Group tests
- Run tests in parallel
- Pass parameters
- Control execution order
Example:
<suite name="Suite">
<test name="Test">
<classes>
<class name="tests.LoginTest"/>
</classes>
</test>
</suite
173. What are groups in TestNG?
Groups are used to categorize test methods.
Example:
@Test(groups = "smoke")
public void loginTest() {
}
You can run only specific groups using testng.xml.
174. What is the use of dependsOnGroups in TestNG?
It allows a test method to depend on an entire group of tests.
Example:
Groups are used to categorize test methods.
Example:
@Test(groups = "smoke")
public void loginTest() {
}
You can run only specific groups using testng.xml.
175. What is dependency in TestNG?
Dependency means one test method depends on another test method.
Example:
@Test
public void login() {
}
@Test(dependsOnMethods = "login")
public void dashboard() {
}
If login() fails, dashboard() will be skipped.
176. What is the difference between Hard Assert and Soft Assert?
Hard Assert
- Stops execution immediately if assertion fails.
Assert.assertEquals(actual, expected);
Soft Assert
- Continues execution even after assertion failure.
SoftAssert sa = new SoftAssert();
sa.assertEquals(actual, expected);
sa.assertAll();
177. What is assertion in TestNG?
Assertions are used to validate expected and actual results.
Common assertions:
- assertEquals()
- assertTrue()
- assertFalse()
- assertNull()
178. What is parameterization in TestNG?
Parameterization allows passing values to test methods from testng.xml.
Example:
<parameter name="browser" value="chrome"/>
@Parameters("browser")
@Test
public void launch(String browser) {
}
179. What is the difference between Parameters and DataProvider?
| Parameters | DataProvider |
| Values from XML | Values from Java method |
| Used for simple data | Used for multiple datasets |
| Less flexible | More flexible |
180. How can you run tests in parallel in TestNG?
Using parallel attribute in testng.xml.
Example:
<suite name="Suite" parallel="tests" thread-count="2">
181. What is invocationCount in TestNG?
It is used to run a test multiple times.
Example:
@Test(invocationCount = 5)
public void testMethod() {
}
182. What is priority in TestNG?
Priority controls execution order of test methods.
Example:
@Test(priority = 1)
public void login() {
}
@Test(priority = 2)
public void logout() {
}
Lower priority executes first.
183. What happens if priority is not set?
Test methods execute in alphabetical order by method name.
184. What is timeout in TestNG?
Timeout defines maximum execution time for a test.
Example:
@Test(timeOut = 3000)
public void test() {
}
Test fails if execution exceeds 3 seconds.
185. What is enabled=false in TestNG?
Used to skip a test method.
Example:
@Test(enabled = false)
public void skipTest() {
}
186. What is the difference between @BeforeTest and @BeforeSuite?
| @BeforeTest | @BeforeSuite |
| Runs before test tag | Runs before entire suite |
| Executes multiple times | Executes once |
187. How do you skip a test in TestNG?
Two ways:
- enabled = false
- Using SkipException
Example:
throw new SkipException("Skipping test")
188. What are listeners in TestNG?
Listeners are interfaces that modify TestNG behavior during execution.
Common listeners:
- ITestListener
- ISuiteListener
Used for:
- Logging
- Screenshots
- Reporting
189. What is ITestListener?
It is a listener interface used to track test execution events.
Methods include:
- onTestStart()
- onTestSuccess()
- onTestFailure()
190. How do you generate reports in TestNG?
TestNG automatically generates reports inside the test-output folder.
Main reports:
- index.html
- emailable-report.html
191. What is factory annotation in TestNG?
@Factory is used to create multiple instances of test classes dynamically.
192. What is the difference between @BeforeTest and @BeforeMethod?
| @BeforeTest | @BeforeMethod |
| Runs before all test methods in a test | Runs before each test method |
| Executes once | Executes multiple times |
193. Can TestNG be integrated with Selenium?
Yes. TestNG is widely used with Selenium for:
- Test execution
- Reporting
- Assertions
- Parallel testing
- Data-driven testing
194. How do you retry failed test cases in TestNG?
Using IRetryAnalyzer.
Example:
public class Retry implements IRetryAnalyzer {
int count = 0;
public boolean retry(ITestResult result) {
if(count < 2) {
count++;
return true;
}
return false;
}
}
195. What is alwaysRun=true in TestNG?
It ensures the method executes even if dependent methods fail.
Example:
@Test(alwaysRun = true)
196. What is thread-count in TestNG?
It defines the number of threads used during parallel execution.
Example:
thread-count="3"
197. What is Page Object Model (POM)?
Page Object Model is a design pattern in Selenium automation where each web page is represented as a separate class.
The class contains:
- Web elements of the page
- Methods to perform actions on those elements
It helps improve:
- Code reusability
- Maintainability
- Readability
198. Why do we use POM in Selenium?
POM is used to:
- Reduce code duplication
- Separate test logic from page elements
- Make framework easy to maintain
- Handle UI changes easily
- Improve scalability of automation framework
199. What are the main components of POM?
Main components are:
- Page Class → Contains locators and methods
- Test Class → Contains test cases
- Object Repository → Stores web element locators
200. What are the advantages of POM?
Advantages:
- Better code organization
- Easy maintenance
- Reusable methods
- Improved readability
- Reduced duplication
- Easy debugging
201. How does POM improve maintainability?
If a locator changes in UI, we update it only in the Page Class instead of updating in all test cases.
202. What is Page Factory in Selenium?
Page Factory is an inbuilt Selenium class used to implement POM easily using annotations like @FindBy.
Example:
@FindBy(id="username")
WebElement userName;
203. Difference between POM and Page Factory?
| POM | Page Factory |
| Uses normal findElement() | Uses @FindBy annotations |
| Elements initialized manually | Elements initialized automatically |
| More coding required | Less coding required |
| Slower compared to Page Factory | Faster initialization |
204. What is the use of @FindBy annotation?
@FindBy is used to locate web elements in Page Factory.
Example:
@FindBy(xpath="//input[@id='email']")
WebElement email;
205. What is PageFactory.initElements()?
It initializes all web elements present in the Page Class.
Example:
PageFactory.initElements(driver, this);
206. How do you create a Page Class in POM?
Example:
public class LoginPage {
WebDriver driver;
@FindBy(id="username")
WebElement username;
@FindBy(id="password")
WebElement password;
@FindBy(id="login")
WebElement loginBtn;
LoginPage(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void login(String user, String pass){
username.sendKeys(user);
password.sendKeys(pass);
loginBtn.click();
}
}
207. What is the role of constructor in POM?
Constructor is used to:
- Initialize WebDriver
- Initialize web elements using PageFactory
208. Can we use POM without Page Factory?
Yes.
We can implement POM using normal findElement() methods without using Page Factory.
209. What is the difference between Page Class and Test Class?
| Page Class | Test Class |
| Contains locators and methods | Contains test cases |
| Represents webpage | Executes validations |
| Reusable | Uses page methods |
210. How does POM support reusability?
Common methods like login, click, search, etc. can be reused across multiple test cases.
211. What type of framework commonly uses POM?
POM is commonly used in:
- Hybrid Framework
- Data-Driven Framework
- Keyword-Driven Framework
212. What are best practices in POM?
- Keep locators private
- Use meaningful method names
- Avoid hard coding
- Use reusable methods
- Maintain separate test and page classes
213. How do you handle dynamic elements in POM?
Dynamic elements can be handled using:
- Dynamic XPath
- Explicit waits
- Relative locators
Example:
@FindBy(xpath="//button[contains(text(),'Login')]")
WebElement loginBtn;
214. Can POM be used with TestNG?
Yes.
POM is commonly integrated with TestNG for test execution, assertions, and reporting.
215. Why is POM considered a good design pattern?
Because it follows:
- Separation of concerns
- Encapsulation
- Reusability
- Maintainability
216. What is encapsulation in POM?
Web elements are hidden inside Page Classes and accessed only through methods.
Example:
public void clickLogin(){
loginBtn.click();
}
217. How do you manage waits in POM?
Waits are usually implemented inside page methods using Explicit Wait.
Example:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOf(loginBtn));
218. How do you handle multiple pages in POM?
Create separate Page Classes for each webpage.
Example:
- LoginPage.java
- HomePage.java
- CartPage.java
219. What is Base Class in POM framework?
Base Class contains common setup code like:
- Browser launch
- Driver initialization
- Wait setup
- Common utilities
220. What are reusable methods in POM?
Methods that can be used multiple times across tests.
Example:
click()
sendKeys()
selectDropdown()
221. How is POM useful in large projects?
In large projects:
- UI changes happen frequently
- Multiple testers work together
- Reusable components are needed
POM helps manage all these efficiently.
222. Explain real-time usage of POM.
In real projects:
- Every page has separate class
- Test cases call page methods
- Framework becomes modular and scalable
- Maintenance becomes easier when UI changes occur
223. What is Log4j?
Log4j is a Java-based logging framework used to generate application logs for debugging, monitoring, and troubleshooting.
224. Why is logging important in automation testing?
Logging helps:
- Track test execution
- Identify failures
- Debug issues easily
- Monitor application behavior
225. What are the main components of Log4j?
- Logger
- Appender
- Layout
226. What is a Logger in Log4j?
Logger is used to capture logging information in the application.
Example:
Logger log = Logger.getLogger(Test.class);
227. What is an Appender?
Appender decides where logs will be stored.
Examples:
- ConsoleAppender
- FileAppender
- RollingFileAppender
228. What is a Layout in Log4j?
Layout defines the format of log messages.
Example:
%d [%t] %-5p %c - %m%n
229. What are the different log levels in Log4j?
| Log Level | Purpose |
|---|---|
| ALL | Logs everything |
| TRACE | Detailed information |
| DEBUG | Debugging information |
| INFO | General information |
| WARN | Warning messages |
| ERROR | Error messages |
| FATAL | Critical errors |
| OFF | Turns off logging |
230. What is the use of log4j.properties file?
It is used to configure:
- Log levels
- Appenders
- Layouts
- Log file location
231. How do you configure Log4j?
Example:
log4j.rootLogger=INFO, file
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=logs/application.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
231. How do you print logs in Log4j?
Example:
log.info("Test Started");
log.error("Test Failed");
log.debug("Debug Message");
233. What is the difference between INFO and DEBUG?
- INFO → General execution information
- DEBUG → Detailed debugging information for developers
234. What is RollingFileAppender?
It creates new log files when file size reaches a limit.
235. What is the advantage of using RollingFileAppender?
- Prevents large log files
- Improves log management
- Creates backup log files automatically
236. What is PatternLayout?
PatternLayout formats log messages in a customizable pattern.
Example:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
237. How is Log4j used in Selenium Automation Framework?
Log4j is used to:
- Log test execution steps
- Capture pass/fail status
- Store exception details
- Debug automation scripts
238. How do you integrate Log4j with Selenium?Steps:
- Add Log4j dependency
- Create log4j.properties file
- Configure logger in Java class
- Use logging methods
239. What dependency is required for Log4j in Maven?
Example:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
240. What is the difference between Log4j and System.out.println()?
| Log4j | System.out.println |
|---|---|
| Professional logging | Simple console printing |
| Supports log levels | No log levels |
| Can store logs in files | Only console output |
| Better for frameworks | Not suitable for large projects |
241. What is Root Logger?
Root Logger is the default logger that controls all child loggers.
Example:
log4j.rootLogger=DEBUG, console
242. What is the difference between Log4j1 and Log4j2?
- Log4j2 is faster
- Better performance
- Supports asynchronous logging
- Improved security