selq1
Q1. write the features file for Login funcatinolity?
Ans:
Feature: Login Functionality
As a registered user,
I want to log in to the mobile application,
So that I can access my account and its features.
Background:
Given the app is launched
Scenario Outline: Login with Different Credentials
Given the user is on the login page
When the user enters "<username>" and "<password>"
And taps the login button
Then the user should see "<expected_result>"
Examples:
| username | password | expected_result |
| validUser | validPass123 | Welcome message displayed |
| invalidUser | validPass123 | Error message displayed |
| validUser | invalidPass | Error message displayed |
| | validPass123 | Validation message displayed |
| validUser | | Validation message displayed |
Scenario: Logout from the Application
Given the user is logged in
When the user navigates to the settings page
And taps the logout button
Then the user should be redirected to the login page
Scenario: Remember Me Functionality
Given the user is on the login page
When the user enters valid "username" and "password"
And selects the "Remember Me" option
And taps the login button
Then the user should be redirected to the home page
And the user session should persist after app restart
Scenario: Password Reset Request
Given the user is on the login page
When the user taps on the "Forgot Password" link
And enters a registered "email address"
And submits the password reset request
Then a password reset confirmation message should be displayed
Scenario: Account Lock After Multiple Failed Attempts
Given the user is on the login page
When the user enters invalid credentials 5 times
Then the account should be locked
And an account lock message should be displayed
Q2. What is Hard Assert and what is Soft assert, Where we can use them and what is preffered?
Ans :
✅ Hard Assert : Immediately halts the test execution if an assertion fails.
Usage: Critical test cases where the failure of a condition should stop further execution.
When to Use:
1. Critical flows like login validation, payment processing, etc.
2. Ensuring test stops when the primary condition is not met.
Pros: Ensures immediate detection of critical failures.
Cons: Stops execution even if other validations are pending.
welcome_message = driver.find_element("id", "welcomeText").text
assert welcome_message == "Welcome", "Login failed: Welcome message not displayed"
import org.testng.Assert;
String welcomeMessage = driver.findElement(By.id("welcomeText")).getText();
Assert.assertEquals(welcomeMessage, "Welcome", "Login failed");
✅ Soft Assert: Collects all assertion failures but does not stop the test immediately.
Execution continues and reports all failures at the end.
Usage: Non-blocking validation like UI checks or verifying multiple outputs.
When to Use:
1. UI validations (e.g., checking multiple labels in one test).
2. When you want to capture multiple issues without stopping execution.
Pros: Executes all assertions and provides a full failure report.
Cons: May allow critical bugs to go unnoticed until the test completes.
from softest import TestCase, soft_assert, assert_all
error_message = driver.find_element("id", "errorText").text
soft_assert(self, error_message == "Invalid Credentials", "Error message mismatch")
page_title = driver.title
soft_assert(self, page_title == "Login Page", "User not on login page")
# Collect all assertions
assert_all()
import org.testng.asserts.SoftAssert;
SoftAssert softAssert = new SoftAssert();
String errorMessage = driver.findElement(By.id("errorText")).getText();
softAssert.assertEquals(errorMessage, "Invalid Credentials", "Error message mismatch");
String pageTitle = driver.getTitle();
softAssert.assertEquals(pageTitle, "Login Page", "User not on login page");
// Collect all assertions
softAssert.assertAll();
Q3. Is fluent wait is applicable throughout the program for the whole program and in what case we use the fluent waits ?
Ans :
✅ What is Fluent Wait?
Fluent Wait in Selenium is a type of explicit wait that allows you to define the maximum amount of time to wait for a condition while checking for the presence of an element at regular intervals.
Unlike implicit wait (which applies globally throughout the entire WebDriver session), fluent wait applies only to a specific element or condition.
📌 Key Features of Fluent Wait:
1. Polling Frequency: Specifies how frequently Selenium checks for the condition (e.g., every 500 ms).
2. Timeout: Maximum time to wait for a condition before throwing an exception.
3. Exception Handling: Can ignore specific exceptions like NoSuchElementException.
4. Element-Specific: Applies to specific actions rather than the entire script.
📊 When to Use Fluent Wait:
1. Dynamic Elements: When elements load dynamically and need periodic checks (e.g., AJAX-based content).
2. Intermittent Conditions: For elements that appear/disappear unpredictably (e.g., success messages).
3. Non-Standard Loads: When dealing with third-party services (e.g., CAPTCHA or iframes).
4. Delayed Actions: If an element appears after a specific action (e.g., submit form, popup display).
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30)) // Maximum wait time
.pollingEvery(Duration.ofSeconds(1)) // Check every 1 second
.ignoring(NoSuchElementException.class); // Ignore this exception
// Wait for the login button to be clickable
WebElement loginButton = wait.until(driver ->
driver.findElement(By.id("loginButton")));
loginButton.click();
Q4. what are the cases where you will use the finally block?
Ans :
1. Closing Database Connections
When interacting with a database (e.g., MySQL, PostgreSQL), connections must be closed to prevent resource leaks.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try
{
connection = DriverManager.getConnection(dbURL, username, password);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next())
{
System.out.println(resultSet.getString("username"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
2. Closing Excel File Streams
When reading from or writing to Excel (using Apache POI), you must close file streams to prevent memory leaks.
'''
FileInputStream fis = null;
Workbook workbook = null;
try
{
fis = new FileInputStream("testData.xlsx");
workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheet("LoginData");
System.out.println(sheet.getRow(1).getCell(0).getStringCellValue());
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (workbook != null) workbook.close();
if (fis != null) fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
3. Quitting WebDriver Instance
In Selenium tests, you should always close the WebDriver instance to free up browser processes.
WebDriver driver = new ChromeDriver();
try
{
driver.get("https://example.com");
System.out.println(driver.getTitle());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (driver != null) {
driver.quit();
}
}
4. Logging or Reporting Cleanup
If you use Extent Reports or other logging tools, the finally block ensures report closure.
'''
ExtentReports extent = new ExtentReports();
try
{
ExtentTest test = extent.createTest("Login Test");
test.pass("Login successful");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
extent.flush(); // Always generate the report
}
Q5. what is 3 amigos
Ans :
The "Three Amigos" is a collaborative approach in Agile software development where three key roles—Business Analyst (BA), Developer (Dev), and Tester (QA)—come together to discuss, refine, and agree on the requirements and acceptance criteria for a feature or user story.
📊 Who Are the Three Amigos?
1. Business Analyst (BA) / Product Owner
Focus: Clarifying business needs and ensuring alignment with customer requirements.
Responsibility: Define and prioritize features, and ensure they deliver business value.
2. Developer (Dev)
Focus: Implementing technical solutions and ensuring feasibility.
Responsibility: Evaluate technical complexity, propose solutions, and deliver working code.
3. Tester (QA)
Focus: Validating that the feature meets acceptance criteria and identifying edge cases.
Responsibility: Ensure quality, define test scenarios, and prevent defects.
📋 Purpose of the Three Amigos Meeting
Shared Understanding: Ensure all stakeholders align on requirements and expected outcomes.
Identify Gaps: Uncover missing scenarios, ambiguous requirements, or technical challenges.
Refine Acceptance Criteria: Define clear, testable acceptance criteria for user stories.
Prevent Rework: Minimize defects and misunderstandings early in the development cycle.
📅 When to Conduct a Three Amigos Session
Before Development Starts: To clarify and refine user stories.
During Sprint Planning: Ensure all team members have a shared understanding.
After Development (Optional): Validate deliverables meet expectations before release.
✅ Example Scenario: Login Feature
If your team is working on a Login feature, a Three Amigos session might look like:
BA: "Users should log in using valid credentials and see a welcome message."
Dev: "We will integrate with the user database and implement session management."
Tester: "We need to test valid/invalid logins, edge cases (empty input), and security checks."
Q6. What is maven surefire plugin?
Ans :
The Maven Surefire Plugin is a key plugin in the Maven build automation tool that is used to run unit tests and integration tests in your Java projects.
It works with popular testing frameworks like: TestNG, JUnit (4, 5), Cucumber
✅ Why is the Surefire Plugin Important?
1. When you run the mvn test command, the Surefire plugin is responsible for:
2. Discovering and executing your test cases.
3. Generating test reports in different formats (e.g., XML, plain text).
4. Controlling parallel execution, retries, and test filters.
✅ Adding Surefire Plugin to pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version> <!-- Ensure this is the latest version -->
</plugin>
</plugins>
</build>
✅ Example with TestNG
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
✅ Key Features of Maven Surefire Plugin :
- Run Specific Tests
mvn test -Dtest=LoginTest
mvn test -Dtest=LoginTest#testValidLogin
2. Parallel Execution
<configuration>
<parallel>methods</parallel>
<threadCount>5</threadCount>
</configuration>
3. Include/Exclude Tests
<configuration>
<includes>
<include>**/LoginTest.java</include>
</includes>
</configuration>
4. Failure Handling (Re-run Failed Tests)
<configuration>
<rerunFailingTestsCount>2</rerunFailingTestsCount>
</configuration>
Q7. You have 10 links how will you print title of each link using selenium. Give optimal approach.
Ans :
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.List;
public class LinkTitlePrinter {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Get all links on the page
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links found: " + links.size());
// Iterate over links and print titles
for (WebElement link : links) {
String linkHref = link.getAttribute("href");
if (linkHref != null && !linkHref.isEmpty()) {
System.out.println("Navigating to: " + linkHref);
// Open link in a new tab using JavaScript
((JavascriptExecutor) driver).executeScript("window.open(arguments[0]);", linkHref);
// Switch to the new tab and get title
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
}
System.out.println("Page Title: " + driver.getTitle());
// Close the tab and return to the main window
driver.close();
driver.switchTo().window(driver.getWindowHandles().iterator().next());
}
}
driver.quit();
}
}
Q8. How would you fetch the text from a alert box in selenium ?
Ans :
Alert alert = driver.switchTo().alert();
// Fetch and print the alert text
System.out.println("Alert Message: " + alert.getText());
Q9. In your Framework, if you have 100 pages, do you create 100 page objects?
Ans :
In a Page Object Model (POM) framework, you don't necessarily create 100 separate page classes for 100 pages—the goal is to keep the framework efficient, maintainable, and modular.
✅ When to Create Separate Page Objects
1. You should create a page object class for each distinct and complex page that has:
2. Unique Elements: If a page has a unique set of web elements (e.g., login page, search page).
3. Frequent Interactions: Pages that require regular interaction (e.g., checkout page, dashboard).
4. Complex Workflows: Multi-step forms or pages with advanced user journeys (e.g., payment page).
✅ When to Reuse or Share Page Objects
Instead of one page = one class, consider these optimizations:
1. Common Components: Extract reusable components like headers, footers, modals into shared classes:
Example: If a search bar appears on multiple pages, create a SearchBarComponent class.
2. Page Inheritance: Use base pages for common functionality across multiple pages:
Example: BasePage for common actions like click(), waitForElement().
3. Dynamic Pages: If multiple pages share a structure, use parameterized methods in one page class:
Example: ProductPage class can handle multiple product details by passing dynamic locators.
Q10. What is an "Element click Intercepted " Exception and how do you fix it?
Ans :
✅ What is an ElementClickInterceptedException in Selenium?
The ElementClickInterceptedException occurs when Selenium tries to click on a web element, but another element overlaps or intercepts the click event.
📌 Common Causes:
1. Pop-ups or Modals: An alert, confirmation, or cookie banner blocking the element.
2. Hidden Elements: Element is present in the DOM but not visible on the page.
3. Sticky Elements: Fixed headers/footers intercepting the click.
4. Page Not Fully Loaded: Clicking before the element is interactable.
5. Animations: Sliding or transitioning elements interfering with the click.
✅ How to Fix ElementClickInterceptedException
📌 1. Scroll to the Element Before Clicking
WebElement element = driver.findElement(By.id("targetElement"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
element.click();
📌 2. Use WebDriverWait for Element Visibility
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("targetElement")));
element.click();
📌 3. Click Using JavaScript
WebElement element = driver.findElement(By.id("targetElement"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", element);
📌 4. Handle Overlapping Elements
// Dismiss a popup if present
try
{
WebElement popup = driver.findElement(By.id("popupCloseButton"));
popup.click();
}
catch (NoSuchElementException e)
{
System.out.println("No popup found.");
}
📌 5. Handle Dynamic Content or Animations
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loadingOverlay")));
📌 6. Use Actions Class for Complex Clicks
WebElement element = driver.findElement(By.id("targetElement"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().perform();
Q11. Why do you prefer using Cucumber bdd in the project?
Ans :
Cucumber is a popular Behavior-Driven Development (BDD) tool that bridges the gap between technical and non-technical stakeholders by writing tests in plain language (Gherkin syntax).
📌 1. Improved Collaboration
Why? Cucumber uses Gherkin language (Given, When, Then) which is easy to understand for developers, testers, product owners, and business analysts.
Example: Non-technical stakeholders can write and review test scenarios without needing to understand the code.
📌 2. Enhanced Test Readability & Documentation
Why? Each scenario acts as living documentation, describing system behavior in plain English.
✅ Benefit: Anyone can understand the test cases—makes the project easier to onboard new team members and maintain.
📌 3. Reusability of Step Definitions
Why? Cucumber allows step reuse across multiple test scenarios using regular expressions.
✅ Benefit: Reduces duplicate code and improves test efficiency.
Q12. How would you conclde that the login Page is user-friendly?
Ans :
1. Ease of Use
* Intuitive Design: Is the login page simple and easy to navigate?
Check: Users should immediately recognize the input fields (e.g., username, password) and action buttons (e.g., "Login", "Forgot Password").
* Clear Labels: Are all labels clear and meaningful?
Check: Labels like “Username”, “Password”, and “Remember Me” should be easy to understand.
2. Efficiency
* Quick Access: Can users log in quickly with minimal steps?
Check: Login should require only essential fields—no unnecessary clicks.
* Auto-Fill Support: Does the page support browser auto-fill for faster login?
Check: Ensure the fields accept saved credentials securely.
3. Error Handling & Feedback
* Clear Error Messages: Are errors descriptive and actionable?
Check: For invalid credentials, display clear error messages like:
"Invalid username or password. Please try again."
* Validation: Are input errors highlighted immediately?
Check: Inform users if a field is left blank or incorrectly filled.
4. Accessibility
* Keyboard Navigation: Can users navigate the page using only the keyboard?
Check: Ensure users can move between fields using the Tab key.
* Screen Reader Compatibility: Is the page accessible to visually impaired users?
Check: Use ARIA labels to describe form elements.
5. Security & Privacy
* Secure Password Handling: Is the password input hidden?
Check: Password should be masked (e.g., ****) and provide a "Show/Hide Password" option.
* Session Management: Are failed login attempts limited?
Check: Implement a lockout mechanism after multiple failed attempts.
6. Mobile Responsiveness
* Adaptive Design: Does the page work seamlessly on mobile devices?
Check: Ensure the page adapts to different screen sizes and orientations.
* Touch-Friendly Elements: Are buttons and fields easy to tap?
Check: Ensure clickable areas are large enough for touchscreens.
7. User Feedback & Testing
* User Satisfaction: Conduct user surveys to gather opinions.
Check: Analyze feedback on ease of use and overall satisfaction.
* A/B Testing: Compare different versions of the login page.
Check: Optimize the page based on real user interaction data.
Q13. What are the five points yo consider while writing a good test cases?
Ans :
📌 1. Clarity and Simplicity
Why: Clear and simple test cases are easier to understand, execute, and maintain.
How:
a. Use concise and unambiguous language.
b. Ensure each test case focuses on a single functionality or user flow.
Example:
-> Bad: Check if login works.
-> Good: Verify that a registered user can successfully log in with valid credentials.
📌 2. Test Coverage
Why: Comprehensive test cases ensure all scenarios (positive, negative, edge cases) are covered.
How:
a. Include positive, negative, and boundary conditions.
b. Ensure test cases cover UI, API, database, and integration levels.
Example: For a login page:
-> Positive: Valid username and password.
-> Negative: Invalid credentials, empty fields.
-> Edge: Long usernames, special characters.
📌 3. Traceability to Requirements
Why: Each test case should map to a specific requirement or user story for better tracking.
How:
a. Use a unique identifier (e.g., TC001).
b. Link test cases to the requirement ID for traceability.
Example:
-> TC001 – Verify login functionality (Linked to User Story: #US101).
📌 4. Reusable and Maintainable
Why: Well-written test cases should be modular and easy to update.
How:
a. Avoid hardcoding values—use parameters where applicable.
b. Create common utility test cases for repetitive steps (e.g., login).
Example:
-> Instead of writing new steps for every test, use a shared login method.
📌 5. Clear Expected Results
Why? Clear outcomes ensure testers know if the test passed or failed.
How?
a. Define the expected behavior for each action.
b. Ensure expected results are measurable and specific.
Example:
-> Step: Enter valid credentials and click login.
-> Expected Result: User is redirected to the dashboard and a welcome message is displayed.
✅ Clarity – Simple, easy-to-read steps.
✅ Coverage – Test all valid, invalid, and edge scenarios.
✅ Traceability – Link test cases to requirements.
✅ Reusability – Modular and easy to update.
✅ Expected Results – Clear, verifiable outcomes.
Q14. Suppose a developer is not fixing a bug; How would you approach the situation?
Ans :
1. Understand the Developer’s Perspective
Why? The developer may have valid reasons for not addressing the bug (e.g., priority conflicts, unclear requirements, or technical challenges).
How?
a. Politely ask the developer why the bug hasn’t been fixed.
b. Clarify if they agree it’s a bug or if there is a disagreement on the issue.
Example Approach:
"Hey [Developer’s Name], I noticed the bug [Bug ID] is still open. Are there any blockers or reasons why it hasn’t been resolved?"
2. Ensure the Bug Report is Clear
Why? Ambiguous or unclear bug descriptions can cause misunderstandings or delays.
How?
Double-check the bug report for clarity:
Steps to Reproduce – Clear and repeatable.
Expected vs. Actual Behavior – Explicit outcomes.
Logs/Screenshots – Provide evidence if needed.
Update the report if it needs more detail.
Example:
"I’ve updated the bug with exact steps and screenshots. Let me know if it’s clear."
3. Prioritize the Bug Correctly
Why? Developers may focus on higher-priority work, causing delays.
How?
Align with stakeholders (QA lead, Product Owner) to reassess the priority.
If the bug impacts a critical feature, escalate its urgency.
Example:
"This bug affects a core functionality in production. Should we prioritize it for the next sprint?"
4. Collaborate, Don’t Blame
Why? Blame can create friction—collaboration fosters resolution.
How?
Offer help if the bug is complex (e.g., provide logs, replicate issues).
Suggest a working session to investigate together.
Example:
"I’m happy to sit down and debug this together if it helps speed things up."
5. Escalate if Necessary (Professionally!)
Why? If unresolved, formal escalation may be needed to maintain quality.
How?
Document your previous efforts and communication.
Involve the QA Lead or Scrum Master to address the block.
Example:
"Despite multiple follow-ups, the bug remains unresolved, impacting release timelines. I’ve flagged it for leadership review."
Q15. How would you open a new tab in selenium?
Ans :
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class TabManager {
private WebDriver driver;
// Constructor to initialize the WebDriver
public TabManager() {
driver = new ChromeDriver();
}
// Method 1: Open a new tab and navigate to a given URL
public String openNewTab(String url) {
driver.switchTo().newWindow(WindowType.TAB);
driver.get(url);
return driver.getWindowHandle(); // Return the handle of the new tab
}
// Method 2: Switch to a specific tab by handle
public void switchToTab(String tabHandle) {
driver.switchTo().window(tabHandle);
}
// Method 3: Iterate through all open tabs and print their titles
public void printAllTabTitles() {
Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
driver.switchTo().window(handle);
System.out.println("Page Title: " + driver.getTitle());
}
}
// Method 4: Close a specific tab by handle
public void closeTab(String tabHandle) {
driver.switchTo().window(tabHandle);
driver.close();
}
// Method 5: Close all tabs except the main tab
public void closeOtherTabs(String mainTab) {
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(mainTab)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(mainTab); // Switch back to the main tab
}
// Method 6: Quit the browser session
public void quit() {
driver.quit();
}
public static void main(String[] args) {
TabManager tabManager = new TabManager();
// Open the main tab
tabManager.driver.get("https://example.com");
String mainTab = tabManager.driver.getWindowHandle();
// Open two additional tabs
String googleTab = tabManager.openNewTab("https://google.com");
String githubTab = tabManager.openNewTab("https://github.com");
// Switch to Google tab and print its title
tabManager.switchToTab(googleTab);
System.out.println("Current Tab Title: " + tabManager.driver.getTitle());
// Print titles of all open tabs
tabManager.printAllTabTitles();
// Close GitHub tab
tabManager.closeTab(githubTab);
// Close all other tabs except the main tab
tabManager.closeOtherTabs(mainTab);
// Final cleanup
tabManager.quit();
}
}
Q16. You are asked to automate a functionality that is not yet fully developed. How would you handel this?
Ans :
Automating a functionality that is not yet fully developed requires a strategic and flexible approach to ensure your tests are robust and adaptable to future changes. Here's how you can handle it effectively:
- Collaborate with Developers Early
a. Understand the Requirements: Discuss the feature with developers and product owners to understand the expected behavior, UI design, and API contracts.
b. Identify Stable Components: Focus on areas that are already stable or unlikely to change (e.g., authentication, navigation, etc.).
2. Implement a Flexible Automation Strategy
a. Use Feature Flags: If available, request feature flags to toggle the incomplete feature on/off for testing.
b. Conditional Execution: Implement checks to skip or disable test cases if the feature is not available.
Example (TestNG approach using @Test(enabled = false)):
@Test
public void testNewFeature() {
if (!isFeatureAvailable()) {
throw new SkipException("Feature not available, skipping test");
}
// Test code
}
3. Use Mocking/Stubbing for Unavailable Parts
Mock External Services: If the feature relies on APIs or databases that are incomplete, use mocking to simulate their responses.
Example using Mock APIs in Java:
MockServerClient mockClient = new MockServerClient("localhost", 1080);
mockClient.when(request().withPath("/api/newFeature"))
.respond(response().withBody("{\"status\":\"success\"}"));
4. Design Your Tests to Be Future-Proof
a. Page Object Model (POM): Keep the locators and actions separate from the tests for easy maintenance.
b. Dynamic Element Handling: Use fluent waits to manage elements that are still being finalized.
5. Implement Placeholder Tests
Write basic tests for the available functionality and TODO comments for unfinished parts.
@Test
public void testFeature() {
// TODO: Add validation when the feature is complete
}
6.Leverage BDD for Collaboration
Use Cucumber BDD scenarios for better alignment with changing requirements.
Scenario: Verify new feature
Given the user is on the homepage
When the new feature is available
Then validate the feature behavior
Q17. If a testcase got failed, What will be your next step?
Ans :
1. Analyze the Failure
a. Check Logs:
* Review the TestNG or Extent Report logs to identify the exact point of failure.
* Ensure you capture both system logs and application logs for a detailed view.
b. Review Screenshots:
* If your framework captures screenshots for failed test cases, examine them to visualize the issue.
Example (Using TestNG @AfterMethod to capture screenshots):
@AfterMethod
public void captureScreenshot(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
Screenshot.capture(driver, result.getName());
}
}
c. Reproduce the Issue Manually:
* Execute the same steps manually in the application to confirm if the issue is consistent or intermittent.
2. Classify the Failure
a. Automation Issue:
* Locator Change: Ensure element locators (XPath, CSS selectors) are not outdated.
* Timing Issues: Use fluent waits to handle dynamic elements.
* Script Error: Validate logic errors in the test script.
b. Application Bug:
* Confirm if the application behavior is incorrect (UI/UX issues, API failures, DB mismatch).
c. Environment/Configuration Issue:
* Ensure test data, browser setup, and dependencies (e.g., SQL connections) are correctly configured.
3. Resolve and Rerun the Test
a. Fix Automation Errors:
* Update locators, adjust wait conditions, and correct test logic if the issue is script-related.
b. Log the Bug:
* If it's an application bug, create a detailed bug report with:
-> Steps to reproduce.
-> Expected vs. Actual behavior.
-> Logs and screenshots.
c. Re-execute the Test:
* Rerun the failed test case after fixing the issue to ensure it passes consistently.
4. Implement Preventive Measures
a. Improve Test Resilience:
* Use retry mechanisms (e.g., IRetryAnalyzer in TestNG) for flaky tests.
* Implement soft assertions for validating multiple conditions without breaking the test.
Example (Using IRetryAnalyzer for automatic retries):
public class RetryAnalyzer implements IRetryAnalyzer {
private int retryCount = 0;
private static final int maxRetryCount = 2;
@Override
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
return true; // Retry the test
}
return false; // Stop retrying
}
}
b. Enhance Reporting:
* Ensure your framework generates detailed reports (e.g., Allure or Extent Reports).
* Integrate with CI/CD pipelines (e.g., Jenkins) to track test failures.
5. Communicate and Document
a. Communicate:
* Share findings with developers and stakeholders for quicker resolution.
b. Document:
* Maintain a failure log for recurring issues and lessons learned.
Q17. your automation script is running slowly. How can yo improve the speed?
Ans:
1. Optimize Wait Strategies
a. Avoid Implicit Waits: Use explicit waits (e.g., WebDriverWait) to wait only for specific elements.
b. Use FluentWait: Poll the DOM periodically instead of waiting for a fixed time.
👉 Example (Java - Explicit Wait):
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("example")));
2. Minimize DOM Interaction
a. Reduce findElement Calls: Store frequently used elements in variables.
b. Use CSS Selectors Over XPaths: CSS is faster to locate elements than XPath.
👉 Example (Better Element Location):
// Fast: CSS Selector
driver.findElement(By.cssSelector(".btn-login"));
// Slow: XPath
driver.findElement(By.xpath("//button[@class='btn-login']"));
3. Optimize Browser Settings
a. Run in Headless Mode: Use headless browsers for faster execution in CI/CD.
b. Disable Unnecessary Features: Turn off images, logs, and animations.
👉 Example (Headless Chrome):
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080");
WebDriver driver = new ChromeDriver(options);
4. Parallel Execution
a. Enable Parallel Testing: Use TestNG with parallel attribute to run tests across multiple threads.
👉 Example (testng.xml Parallel Setup):
<suite name="Suite" parallel="methods" thread-count="5">
<test name="Test">
<classes>
<class name="tests.MyTest"/>
</classes>
</test>
</suite>
5. Avoid Hardcoded Waits
a. Replace Thread.sleep() with dynamic waits to avoid unnecessary pauses.
-
Optimize Test Data Management
a. Use lightweight in-memory databases or mock services instead of external databases during testing. -
Use Fast Locators
a. Prefer ID or ClassName locators over XPath and LinkText for faster element identification. -
Improve Driver and Session Management
a. Reuse WebDriver sessions for multiple tests instead of creating a new session for each test.
Q18. How would you automate a scenario where you need to v alidate the content of a download file after clicking a button on a webpage?
Ans :
Approach Overview:
* Click the download button to initiate the file download.
* Wait until the download is completed.
* Locate the downloaded file in the system's download directory.
* Open and validate the content of the downloaded file.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.Duration;
public class DownloadFileValidation {
public static void main(String[] args) throws IOException {
// Set download directory
String downloadPath = "C:\\Users\\YourUser\\Downloads";
// Configure ChromeOptions to set download path
ChromeOptions options = new ChromeOptions();
options.addArguments("download.default_directory=" + downloadPath);
WebDriver driver = new ChromeDriver(options);
try {
// Open the webpage
driver.get("https://example.com/download-page");
// Click the download button
driver.findElement(By.id("downloadButton")).click();
// Wait for the download to complete (polling mechanism)
File downloadedFile = waitForDownload(downloadPath, "sample.txt");
System.out.println("File downloaded: " + downloadedFile.getName());
// Validate content of the file
validateFileContent(downloadedFile, "Expected content inside the file");
} finally {
driver.quit();
}
}
// Helper method to wait for file download
public static File waitForDownload(String downloadPath, String fileName) {
File file = new File(downloadPath, fileName);
int waitTime = 30; // seconds
while (waitTime > 0) {
if (file.exists()) return file;
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
waitTime--;
}
throw new RuntimeException("File not downloaded: " + fileName);
}
// Helper method to validate file content
public static void validateFileContent(File file, String expectedContent) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
boolean contentMatch = false;
while ((line = reader.readLine()) != null) {
if (line.contains(expectedContent)) {
contentMatch = true;
break;
}
}
if (contentMatch) {
System.out.println("File content is valid!");
} else {
throw new AssertionError("File content validation failed.");
}
}
}
}
Explanation:
a. Set Download Directory: Configure ChromeOptions to define a custom download folder.
b. Click and Wait for Download: Use a polling loop to wait for the file to appear in the download folder.
c. Validate File Content: Read the downloaded file and check if it contains the expected content.
d. Clean Up: Ensure to quit the driver after the validation process.
Q19. How would you automate a scenario where you need to verify that if a user is able to scroll down a webpage untill the footer section is visible?
Ans:
WebElement footer = driver.findElement(By.id("footer"));
// Scroll to the footer using JavaScript Executor
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", footer);
// Verify if the footer is displayed
if (footer.isDisplayed()) {
System.out.println("Footer is visible - Scroll successful!");
} else {
System.out.println("Footer is NOT visible - Scroll failed!");
}
Question to consider :
- Write the selenium code to automate a calander web Element?
- How would you pick the test cases for regression testing?
- Explain the static binding and Dynamic Binding?
- in jenkins, what is the purpose of a cron expression?
- If the application has minor changes, what would be your approach to modifying the automation script?
- How would you automate a test scenario where you need to check if an email is sent after a user registration?
- How would you automate a scenario that takes a long time to execute, wold you prefer Manual testing or Automating Testing?
- How to run the selenium script on already opened browser?