-->

Featured

DSA Interview Question

Question: Various S orting algorithms Answer: There are various sorting algorithms, each with its own advantages and disadvantages in terms ...

PlayWright

Question: What is Playwright?

Answer:

Playwright is an open-source end-to-end automation testing framework developed by Microsoft. It supports automation of Chromium, Firefox, and WebKit browsers using a single API. Playwright provides fast, reliable, and cross-browser testing with built-in support for auto-waiting, multiple browser contexts, network interception, screenshots, videos, and parallel execution.


Question: What are the key features of Playwright?

Answer:

  • Supports Chromium, Firefox, and WebKit.
  • Cross-platform support (Windows, Linux, macOS).
  • Supports JavaScript, TypeScript, Java, Python, and .NET.
  • Automatic waiting for elements.
  • Supports multiple browser contexts.
  • Parallel test execution.
  • Network interception and API mocking.
  • Captures screenshots, videos, and traces.
  • Supports mobile device emulation.

Question: Which browsers are supported by Playwright?

Answer:

Playwright supports the following browsers:

  • Google Chrome / Chromium
  • Microsoft Edge
  • Mozilla Firefox
  • Safari (WebKit)

Question: What is Browser Context in Playwright?

Answer:

A Browser Context is an isolated browser session. Multiple contexts can run inside a single browser instance without sharing cookies, cache, or local storage. It is useful for testing multiple users simultaneously.

Example: Create a browser context.

const browser = await chromium.launch();

const context = await browser.newContext();

const page = await context.newPage();

Note: Browser Contexts are lightweight and faster than launching multiple browser instances.


Question: What is the difference between Browser and Browser Context?

Answer:

Browser:

  • Represents the browser application.
  • Consumes more resources.
  • Can contain multiple browser contexts.

Browser Context:

  • Represents an isolated browser session.
  • Shares the browser process.
  • Has separate cookies, cache, and storage.

Question: What is auto-waiting in Playwright?

Answer:

Playwright automatically waits for elements before performing actions. It waits until the element becomes:

  • Visible
  • Stable
  • Enabled
  • Ready to receive events

Example:

await page.locator("#login").click();

Note: Unlike Selenium, Playwright usually does not require explicit waits before clicking or typing.


Question: How do you launch a browser in Playwright?

Answer:

Example: Launch Chromium browser.

import { chromium } from '@playwright/test';

const browser = await chromium.launch({
    headless: false
});

const page = await browser.newPage();

await page.goto("https://example.com");

Question: How do you locate elements in Playwright?

Answer:

Playwright provides multiple locator strategies.

  • getByRole()
  • getByText()
  • getByLabel()
  • getByPlaceholder()
  • getByAltText()
  • getByTitle()
  • getByTestId()
  • locator()
  • CSS Selector
  • XPath

Example:

await page.getByRole('button', {
    name: 'Login'
}).click();

await page.locator("#username").fill("admin");

Question: What is Locator in Playwright?

Answer:

A Locator represents a way to find elements on the page. It automatically retries until the element satisfies the required conditions, making tests more reliable.

Example:

const loginButton = page.locator("#login");

await loginButton.click();

Question: What is the difference between Locator and ElementHandle?

Answer:

Locator:

  • Automatically waits for elements.
  • Retries until action succeeds.
  • Recommended by Playwright.

ElementHandle:

  • Represents a fixed DOM element.
  • Does not auto-retry.
  • Can become stale if the DOM changes.

Note: Prefer using Locators instead of ElementHandle.


Question: How do you take screenshots in Playwright?

Answer:

Example: Capture the full page screenshot.

await page.screenshot({
    path: "homepage.png",
    fullPage: true
});

Question: How do you upload a file in Playwright?

Answer:

Example:

await page.locator("input[type='file']")
    .setInputFiles("sample.pdf");

Question: How do you handle alerts in Playwright?

Answer:

Playwright listens for dialog events.

Example:

page.on("dialog", async dialog => {
    console.log(dialog.message());
    await dialog.accept();
});

await page.locator("#alert").click();

Question: How do you perform assertions in Playwright?

Answer:

Playwright provides built-in assertions through the expect() API.

Example:

await expect(page).toHaveTitle("Home");

await expect(page.locator("#login"))
    .toBeVisible();

Question: What is Trace Viewer in Playwright?

Answer:

Trace Viewer is a debugging tool that records every action performed during test execution, including screenshots, DOM snapshots, console logs, network requests, and timing information.

Example: Enable tracing.

await context.tracing.start({
    screenshots: true,
    snapshots: true
});

...

await context.tracing.stop({
    path: "trace.zip"
});

Note: Trace Viewer is one of the most powerful debugging features available in Playwright.

Question: How do you navigate to a URL in Playwright?

Answer:

Playwright uses the goto() method to navigate to a web page.

Example: Navigate to a website.

await page.goto("https://www.google.com");

Note: The goto() method waits until the page reaches the default load state before continuing.


Question: How do you perform mouse actions in Playwright?

Answer:

Playwright provides various mouse actions such as click, double-click, right-click, hover, and drag-and-drop.

Example: Mouse actions.

// Click
await page.locator("#btn").click();

// Double Click
await page.locator("#btn").dblclick();

// Right Click
await page.locator("#btn").click({
    button: "right"
});

// Hover
await page.locator("#menu").hover();

Question: How do you perform keyboard actions in Playwright?

Answer:

Keyboard actions are performed using the keyboard object.

Example:

await page.keyboard.type("Playwright");

await page.keyboard.press("Enter");

await page.keyboard.press("Control+A");

await page.keyboard.press("Backspace");

Question: How do you handle dropdowns in Playwright?

Answer:

The selectOption() method is used to select values from a dropdown.

Example:

await page.locator("#country")
    .selectOption("India");

await page.locator("#country")
    .selectOption({ label: "India" });

await page.locator("#country")
    .selectOption({ index: 2 });

Question: How do you check or uncheck a checkbox in Playwright?

Answer:

Playwright provides dedicated methods to work with checkboxes.

Example:

await page.locator("#agree").check();

await page.locator("#agree").uncheck();

await expect(page.locator("#agree"))
    .toBeChecked();

Question: How do you work with radio buttons in Playwright?

Answer:

Radio buttons can be selected using the check() method.

Example:

await page.locator("#male").check();

await expect(page.locator("#male"))
    .toBeChecked();

Question: How do you handle multiple tabs in Playwright?

Answer:

Playwright uses the waitForEvent('page') method to capture newly opened tabs.

Example:

const pagePromise =
    context.waitForEvent("page");

await page.locator("#newTab").click();

const newPage = await pagePromise;

await newPage.waitForLoadState();

Question: How do you handle multiple browser windows in Playwright?

Answer:

Every newly opened browser window is represented as a new Page object.

Example:

const popupPromise =
    page.waitForEvent("popup");

await page.locator("#window")
    .click();

const popup = await popupPromise;

await popup.waitForLoadState();

Question: How do you handle file downloads in Playwright?

Answer:

Playwright provides download events for handling downloaded files.

Example:

const downloadPromise =
    page.waitForEvent("download");

await page.locator("#download")
    .click();

const download =
    await downloadPromise;

await download.saveAs("report.pdf");

Question: How do you perform drag and drop in Playwright?

Answer:

Playwright provides the dragTo() method.

Example:

await page.locator("#source")
    .dragTo(
        page.locator("#target")
    );

Question: How do you scroll a page in Playwright?

Answer:

Pages can be scrolled using JavaScript or locator methods.

Example:

await page.evaluate(() => {
    window.scrollTo(0,
    document.body.scrollHeight);
});

await page.locator("#footer")
    .scrollIntoViewIfNeeded();

Question: How do you execute JavaScript in Playwright?

Answer:

The evaluate() method executes JavaScript inside the browser.

Example:

String title =
await page.evaluate(() =>
document.title);

await page.evaluate(() => {
    localStorage.clear();
});

Question: How do you wait for an element in Playwright?

Answer:

Although Playwright automatically waits for most actions, explicit waiting is available when needed.

Example:

await page.locator("#login")
    .waitFor();

await page.waitForSelector(
    "#username"
);

Note: Explicit waits should be used only when auto-waiting is insufficient.


Question: How do you handle authentication in Playwright?

Answer:

Authentication state can be saved and reused to avoid logging in before every test.

Example:

await context.storageState({
    path: "auth.json"
});

Example: Reuse authentication.

const context =
await browser.newContext({
    storageState: "auth.json"
});

Question: What is Playwright Test Runner?

Answer:

Playwright Test Runner is the built-in testing framework that supports:

  • Parallel execution.
  • Retries.
  • Fixtures.
  • Projects.
  • HTML reports.
  • Screenshots.
  • Video recording.
  • Trace Viewer.

Question: What are Fixtures in Playwright?

Answer:

Fixtures are reusable setup and teardown components shared across tests.

Example:

test("Login Test",
async ({ page }) => {

    await page.goto(
        "https://example.com"
    );

});

Note: The page object is provided automatically by the Playwright fixture.


Question: How do you run tests in parallel in Playwright?

Answer:

Parallel execution is configured using the workers property.

Example:

export default defineConfig({

    workers: 4

});

Question: How do you retry failed tests in Playwright?

Answer:

The retries option automatically reruns failed tests.

Example:

export default defineConfig({

    retries: 2

});

Question: How do you generate an HTML report in Playwright?

Answer:

Playwright can generate rich HTML reports after test execution.

Example:

export default defineConfig({

    reporter: "html"

});

Command:

npx playwright show-report

Question: Why is Playwright preferred over Selenium?

Answer:

  • Built-in auto waiting.
  • Faster execution.
  • Supports Chromium, Firefox, and WebKit.
  • No separate browser drivers are required.
  • Supports network interception.
  • Supports parallel execution by default.
  • Built-in screenshots, videos, and tracing.
  • Provides more reliable locators.
  • Excellent debugging capabilities.

Note: Playwright is increasingly adopted for modern web application testing because of its speed, stability, and rich feature set.

Question: How do you handle dynamic web elements in Playwright?

Answer:

Dynamic web elements frequently change their attributes such as id, class, or name. In Playwright, it is recommended to use stable locators like getByRole(), getByLabel(), getByTestId(), or CSS selectors instead of dynamic IDs.

Example: Using a stable locator.

await page.getByRole("button", {
    name: "Login"
}).click();

Note: Avoid using dynamically generated IDs whenever possible.


Question: How do you handle hidden elements in Playwright?

Answer:

Hidden elements cannot be interacted with until they become visible. Playwright automatically waits for elements to become visible before performing actions.

Example:

await page.locator("#submit")
    .waitFor();

await page.locator("#submit")
    .click();

Question: How do you handle loading spinners in Playwright?

Answer:

Wait until the loading spinner disappears before interacting with page elements.

Example:

await page.locator(".loader")
    .waitFor({
        state: "hidden"
    });

await page.locator("#save")
    .click();

Question: How do you verify toast messages in Playwright?

Answer:

Locate the toast notification and verify its text using Playwright assertions.

Example:

await expect(
    page.locator(".toast")
).toHaveText(
    "Record Saved Successfully"
);

Question: How do you handle network API calls in Playwright?

Answer:

Playwright provides waitForResponse() to wait until a specific API call completes.

Example:

await Promise.all([

page.waitForResponse(
response =>
response.url().includes("/login")
&& response.status() == 200
),

page.locator("#login")
.click()

]);

Note: This is more reliable than using fixed waits.


Question: How do you mock API responses in Playwright?

Answer:

Playwright allows intercepting network requests using the route() method.

Example:

await page.route(
"**/users",
route => {

route.fulfill({

status:200,

body: JSON.stringify([
{
name:"John"
}
])

});

});

Question: How do you block unnecessary network requests in Playwright?

Answer:

Images, fonts, and advertisements can be blocked to improve execution speed.

Example:

await page.route(

"**/*.{png,jpg,jpeg,gif}",

route => route.abort()

);

Question: How do you handle stale element problems in Playwright?

Answer:

Unlike Selenium, Playwright locators automatically re-query the DOM before every action, reducing stale element issues.

Example:

await page.locator("#login")
.click();

Note: Always use Locator instead of storing ElementHandle objects.


Question: How do you capture browser console logs in Playwright?

Answer:

Console messages can be captured using the console event.

Example:

page.on("console",

msg => {

console.log(msg.text());

});

Question: How do you capture failed screenshots automatically?

Answer:

Configure Playwright Test to capture screenshots only for failed tests.

Example:

export default defineConfig({

use:{

screenshot:
"only-on-failure"

}

});

Question: How do you record videos of failed tests?

Answer:

Playwright can automatically record videos during test execution.

Example:

export default defineConfig({

use:{

video:
"retain-on-failure"

}

});

Question: How do you perform data-driven testing in Playwright?

Answer:

Use JavaScript arrays, JSON files, or CSV files to execute the same test with multiple datasets.

Example:

const users = [

"Admin",

"Manager",

"Guest"

];

for(const user of users){

test(user,

async ({page})=>{

// Test logic

});

}

Question: How do you run the same test in multiple browsers?

Answer:

Playwright Projects allow the same test to run on Chromium, Firefox, and WebKit.

Example:

projects:[

{
name:"Chromium"
},

{
name:"Firefox"
},

{
name:"WebKit"
}

]

Question: How do you handle environment-specific URLs in Playwright?

Answer:

Store URLs inside environment variables or configuration files instead of hardcoding them.

Example:

await page.goto(

process.env.BASE_URL!

);

Question: How do you organize a Playwright automation framework?

Answer:

  • Page Object Model (POM).
  • Utility classes.
  • Common fixtures.
  • Test data folder.
  • Environment configuration.
  • API helper classes.
  • Custom reporting.
  • Reusable assertions.

Note: A well-structured framework improves code reusability and maintainability.


Question: A button is visible but Playwright cannot click it. How would you troubleshoot?

Answer:

  • Verify the locator.
  • Check if another element overlaps the button.
  • Wait for animations to complete.
  • Verify the element is enabled.
  • Inspect browser console errors.
  • Use Trace Viewer for debugging.
  • Check if the button is inside an iframe.

Example:

await expect(
page.locator("#save")
).toBeVisible();

await expect(
page.locator("#save")
).toBeEnabled();

await page.locator("#save")
.click();

Question: What is the difference between page.waitForSelector() and Locator in Playwright?

Answer:

Locator is the recommended approach in Playwright because it automatically waits for elements before every action, whereas page.waitForSelector() waits only once and returns an ElementHandle.

Locator:

  • Automatically retries until the action succeeds.
  • Supports auto waiting.
  • Recommended by Playwright.

waitForSelector():

  • Returns an ElementHandle.
  • Can become stale if the DOM changes.
  • Mainly used for legacy code.

Example:

await page.locator("#login").click();

Note: Prefer Locator APIs over waitForSelector() in new projects.


Question: How do you handle Shadow DOM elements in Playwright?

Answer:

Playwright automatically pierces open Shadow DOM, so no special API is required.

Example:

await page
.locator("custom-component")
.locator("#username")
.fill("admin");

Note: Closed Shadow DOM cannot be accessed by any automation framework.


Question: How do you intercept and modify API requests in Playwright?

Answer:

The route() method allows modification of outgoing requests before they reach the server.

Example:

await page.route("**/login",

async route=>{

const request=route.request();

const data=request.postDataJSON();

data.username="Admin";

await route.continue({

postData:JSON.stringify(data)

});

});

Question: How do you verify REST API responses while testing UI in Playwright?

Answer:

Use waitForResponse() and validate the response body before continuing with UI validation.

Example:

const response=
await page.waitForResponse(

res=>res.url().includes("/users")

);

expect(response.status())
.toBe(200);

const body=
await response.json();

Question: How do you test WebSocket communication in Playwright?

Answer:

Playwright allows listening to WebSocket events for validating real-time communication.

Example:

page.on("websocket",

ws=>{

console.log(ws.url());

});

Question: How do you test file downloads without saving them to disk?

Answer:

The download object can be inspected without permanently storing the file.

Example:

const download=

await page.waitForEvent(
"download"
);

console.log(

download.suggestedFilename()

);

Question: How do you reduce flaky tests in Playwright?

Answer:

  • Use Locators instead of ElementHandle.
  • Avoid fixed waits.
  • Wait for API responses instead of UI delays.
  • Use stable selectors.
  • Use Browser Context isolation.
  • Use retries only as a last resort.
  • Review traces for failures.

Note: Most flaky tests are caused by synchronization issues rather than Playwright itself.


Question: How do you test multiple users simultaneously in Playwright?

Answer:

Create multiple Browser Contexts within the same browser instance.

Example:

const admin=

await browser.newContext();

const customer=

await browser.newContext();

const adminPage=

await admin.newPage();

const customerPage=

await customer.newPage();

Question: How do you handle authentication using API instead of UI login?

Answer:

Login using Playwright's APIRequestContext, store the authentication state, and reuse it across tests.

Example:

await request.post(

"/login",

{

data:{

username:"admin",

password:"admin"

}

});

Note: API login significantly reduces execution time.


Question: What is APIRequestContext in Playwright?

Answer:

APIRequestContext allows sending HTTP requests directly without opening a browser.

Example:

const response=

await request.get(

"/users"

);

expect(response.ok())

.toBeTruthy();

Question: How do you test responsive websites in Playwright?

Answer:

Create browser contexts with different viewport sizes or use built-in device emulation.

Example:

const context=

await browser.newContext({

viewport:{

width:390,

height:844

}

});

Question: How do you debug failed Playwright tests?

Answer:

  • Trace Viewer.
  • Inspector Mode.
  • Screenshots.
  • Videos.
  • Console Logs.
  • Network Logs.
  • PWDEBUG environment variable.

Example:

PWDEBUG=1

npx playwright test

Question: Explain the execution flow of Playwright.

Answer:

  • Playwright Test Runner starts execution.
  • Browser launches.
  • Browser Context is created.
  • Page object is initialized.
  • Locators identify elements.
  • Auto waiting ensures readiness.
  • Actions are performed.
  • Assertions validate results.
  • Reports, screenshots, videos and traces are generated.

Question: What are the best practices for designing a Playwright framework?

Answer:

  • Use Page Object Model.
  • Separate test data.
  • Create reusable utility classes.
  • Implement custom fixtures.
  • Use environment configuration.
  • Generate HTML reports.
  • Enable tracing for failures.
  • Use TypeScript instead of JavaScript.
  • Avoid duplicate locators.
  • Follow SOLID principles.

Question: Your Playwright tests pass locally but fail in Jenkins. How would you investigate?

Answer:

  • Compare browser versions.
  • Verify Playwright version.
  • Check environment variables.
  • Review Jenkins logs.
  • Inspect screenshots and traces.
  • Verify network availability.
  • Check headless-specific issues.
  • Verify permissions and file paths.
  • Look for timing differences.
  • Run the failed test with Trace Viewer.

Note: Environment differences are the most common cause of CI/CD failures.

Question: What are the different types of Assertions available in Playwright?

Answer:

Playwright provides two types of assertions:

  • Auto-Retry Assertions – Automatically wait until the expected condition becomes true.
  • Non-Retry Assertions – Immediately verify the condition without waiting.

Common Auto-Retry Assertions:

  • toBeVisible()
  • toBeHidden()
  • toBeEnabled()
  • toBeDisabled()
  • toBeEditable()
  • toBeChecked()
  • toBeEmpty()
  • toContainText()
  • toHaveText()
  • toHaveValue()
  • toHaveCount()
  • toHaveAttribute()
  • toHaveClass()
  • toHaveCSS()
  • toHaveId()
  • toHaveJSProperty()
  • toHaveRole()
  • toHaveTitle()
  • toHaveURL()

Example:

await expect(
page.locator("#login")
).toBeVisible();

Question: Explain commonly used Playwright Assertions with descriptions.

Answer:

Assertion Description
toBeVisible() Verifies that an element is visible.
toBeHidden() Verifies that an element is hidden.
toBeEnabled() Checks whether an element is enabled.
toBeDisabled() Checks whether an element is disabled.
toBeEditable() Checks whether an input field is editable.
toBeChecked() Verifies checkbox or radio button selection.
toHaveText() Verifies exact text.
toContainText() Verifies partial text.
toHaveValue() Verifies input field value.
toHaveCount() Verifies number of matching elements.
toHaveAttribute() Verifies an attribute value.
toHaveClass() Verifies CSS class.
toHaveCSS() Verifies CSS property value.
toHaveTitle() Verifies page title.
toHaveURL() Verifies current URL.

Question: What are the different Actions supported in Playwright?

Answer:

Playwright provides various built-in actions for interacting with web elements.

Action Description
click() Clicks an element.
dblclick() Double-clicks an element.
check() Selects a checkbox.
uncheck() Unselects a checkbox.
fill() Enters text into an input field.
clear() Clears an input field.
hover() Moves mouse over an element.
dragTo() Performs drag and drop.
focus() Sets focus on an element.
press() Presses a keyboard key.
pressSequentially() Types characters one by one.
setInputFiles() Uploads files.
selectOption() Selects dropdown values.
scrollIntoViewIfNeeded() Scrolls to the element.
screenshot() Takes element screenshot.

Question: What are the different Locator methods available in Playwright?

Answer:

Playwright provides multiple modern locator strategies.

Locator Description
locator() Generic locator using CSS or XPath.
getByRole() Finds elements using ARIA role.
getByText() Finds element by visible text.
getByLabel() Finds input using associated label.
getByPlaceholder() Finds element using placeholder.
getByAltText() Finds image using alt text.
getByTitle() Finds element using title attribute.
getByTestId() Finds element using test-id.
frameLocator() Locates elements inside iframe.

Question: What are the commonly used Page methods in Playwright?

Answer:

Method Description
goto() Navigate to URL.
reload() Reload current page.
goBack() Navigate back.
goForward() Navigate forward.
title() Returns page title.
url() Returns current URL.
content() Returns page HTML.
evaluate() Executes JavaScript.
waitForLoadState() Waits until page loads.
waitForResponse() Waits for API response.
waitForRequest() Waits for request.
waitForEvent() Waits for browser events.
route() Intercepts network requests.
screenshot() Takes page screenshot.
pdf() Generates PDF (Chromium).

Question: What are the commonly used Browser Context methods?

Answer:

Method Description
newPage() Creates a new page.
close() Closes browser context.
cookies() Returns cookies.
clearCookies() Deletes cookies.
grantPermissions() Grants browser permissions.
storageState() Saves authentication state.
addInitScript() Runs JavaScript before page loads.
setDefaultTimeout() Sets default timeout.

SDET interview questions

 Question: Can you describe the key components of a well-structured test automation framework?

Answer: 

Key Components of a Well-Structured Automation Framework

  1. Modularity – The framework should follow a layered approach (e.g., Page Object Model for UI tests) for better maintenance.

  2. Reusability – Common functions (like login, API calls, or database queries) should be written as reusable utilities.

  3. Scalability – It should support adding new test cases and integrating with various tools easily.

  4. Maintainability – Proper logging, reporting (e.g., Extent Reports, Allure), and exception handling should be in place.

  5. Integration with CI/CD – The framework should run seamlessly in Jenkins/GitHub Actions or any other CI/CD pipeline.

 Question: How do you decide which framework to use for a project? What factors do you consider?

Answer: 

Factors for Selecting a Test Automation Framework

  1. Project Requirements – UI vs. API testing, frequency of execution, and type of application.

  2. Data Handling – If extensive data variations are needed, a Data-Driven approach (using Excel, JSON, or databases) is suitable.

  3. Maintainability – If the application has frequent UI changes, Page Object Model (POM) helps keep locators and logic separate.

  4. Parallel Execution – If speed is a concern, frameworks like TestNG (for parallel execution) or WebDriverIO with Grid can be useful.

  5. Technology Stack – If the development team is using JavaScript-based tools, WebDriverIO or Cypress might be a better fit over Selenium.

  6. CI/CD Integration – If seamless integration with Jenkins, GitHub Actions, or Azure DevOps is required, choosing a framework with built-in support helps.

 Question: If an API request is failing with a 500 Internal Server Error, how do you debug the issue?

Answer: A 500 error means there’s an issue on the server side, but as a tester, you can help identify the root cause.

1️⃣ Validate the API Request

  • Check Request Body – Ensure JSON/XML is correctly formatted and contains required fields.

  • Check Headers – Ensure Content-Type, Authorization, and other headers are correct.

  • Check API Endpoint – Confirm you’re hitting the correct URL and method (GET/POST/PUT/DELETE).

2️⃣ Inspect API Response Details

  • Check Response Message – Some APIs provide detailed error messages in the response body.

  • Check Logs – If you have access to server logs, review them for exact error details.

3️⃣ Try Different Test Data

  • ✅ Use valid and invalid payloads to see if the issue occurs with specific inputs.

  • ✅ Check if the issue happens only for a specific user, role, or scenario.

4️⃣ Debug Using Tools

  • Postman or ReadyAPI – Try sending the same request manually and compare responses.

  • Check API Monitoring Tools – If the API is tracked in New Relic, Datadog, or Kibana, review logs for failures.

5️⃣ Collaborate with Developers

  • ✅ If everything looks correct on your end, escalate with API request/response logs to the development team.

  • ✅ Ask if there were recent code changes or deployments that could have caused the issue.

 Question: How would you handle API test automation failures in a CI/CD pipeline? How do you ensure tests are reliable?

Answer: 

Handling API Test Automation Failures in CI/CD

When API tests run in a Jenkins/GitHub Actions/Azure DevOps pipeline, failures can happen due to:

  1. Environment Issues (e.g., API server down, incorrect base URL).

  2. Data Dependencies (e.g., missing test data).

  3. Network Flakiness (e.g., slow response, timeout).

  4. Code Changes (e.g., API contract updates).

How to Handle Failures Effectively:

1. Retry Mechanism – If a test fails due to a timeout or network issue, retry it before marking it failed.

given()

    .when().get("/users")

    .then().statusCode(200)

    .retry(3); // Retries 3 times before failing

  • In CI/CD, configure retries using a retry plugin (e.g., Jenkins Retry Plugin).

2. Use Mock Servers for Stability – Instead of always hitting a live API, use WireMock or Postman Mock Server for predictable responses.

3. Validate Response Before Assertions – If a request fails, first check if the response is valid before running assertions:

4. Parameterize Environment URLs – Use separate configs for Dev, QA, and Prod to avoid environment mismatches.

String baseUrl = System.getProperty("env", "https://dev.api.com");


 Question: If a test case is failing intermittently (flaky test), how would you debug and fix it?

Answer: A flaky test is a test that sometimes passes and sometimes fails without any code changes.

1️⃣ Manually Verify the Issue

✅ Run the test manually to check if the issue is real or caused by test script instability.
✅ If it’s a genuine bug, log a defect and escalate it to the developers.

2️⃣ Identify the Root Cause

✅ If the issue is not reproducible manually, check for these common causes:

  • DOM Changes – Verify if element locators (XPath, CSS) have changed.

  • Timing Issues – API calls, animations, or page loads may be slower in some cases.

  • Test Data Issues – Ensure correct test data is used.

  • Parallel Execution Conflicts – Tests interfering with each other in CI/CD.

3️⃣ Apply Fixes to Stabilize Tests

🔹 Use Dynamic & Stable Locators

  • Avoid absolute XPath (/html/body/div[1]/table/tr[3]/td[2]).

  • Prefer CSS Selectors or Relative XPath:

🔹 Implement Smart Waits

  • Instead of Thread.sleep(), use Explicit Waits to handle dynamic elements:

🔹 Use Retry Mechanism

  • If a test fails due to a temporary issue, retry it before marking it as failed.

🔹 Ensure Test Isolation in CI/CD

  • Use unique test data to prevent conflicts.

  • Run tests in separate environments or use mock servers (e.g., WireMock).

 Question: If a parallel test fails intermittently, how would you debug and fix it?

Answer: 

 Check Test Case Independence

🔹 Ensure each test runs independently without modifying shared test data.
🔹 Fix: Use unique test data for each test case:

  • Generate random data dynamically (UUID.randomUUID().toString()).

  • Use separate test users instead of a single user.

Example: Generating Unique Test Data

2️⃣ Isolate Browser Sessions Properly

🔹 If a test modifies cookies, local storage, or session, it might affect others running in parallel.
🔹 Fix: Use incognito mode or different browser profiles.

Example: Running WebDriverIO Tests in Incognito Mode

3️⃣ Use Explicit Waits for Stability

🔹 Issue: Elements take time to load, causing test failures.
🔹 Fix: Replace Thread.sleep() with Explicit Waits.

Example: Wait Until Element is Clickable

4️⃣ Debug Flaky Tests with Logging & Screenshots

🔹 Enable detailed logs to track why tests fail randomly.
🔹 Fix: Capture logs and screenshots automatically on failure.

Example: Capture Screenshot on Failure

5️⃣ Run Tests in Clean State

🔹 If a test modifies global state (DB, API, or UI settings), ensure it's reset.
🔹 Fix:

  • Use a setup/teardown mechanism to clean data before/after each test.

  • Run API calls to reset test users after execution.

Example: Clean Up Data in afterEach() Hook


Final Thoughts

✅ Ensure tests don’t share data in parallel execution.
✅ Use unique browser sessions to prevent conflicts.
✅ Add logging, retries, and cleanup for stable test runs.

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 

 Question: 

Answer: 


Maven Questions

Question: What is Maven and why is it used in automation project
Answer:Maven is a build automation and dependency management tool for Java-based projects. It’s used to:
  • Manage project dependencies through a centralized pom.xml file.

  • Compile, test, package and deploy applications.

  • Integrate with CI tools like Jenkins for continuous execution.

  • Ensure standard project structure and reproducibility across teams.


Question: Explain Maven lifecycle?
Answer: 

Types of Maven Lifecycles

Maven has 3 built-in lifecycles:

1️⃣ Default Lifecycle – Build & test the project
2️⃣ Clean Lifecycle – Clean old build files
3️⃣ Site Lifecycle – Generate project documentation


1️⃣ Clean Lifecycle - Deletes the target/ folder.

Used to remove previous build artifacts.

Phases:

pre-clean → clean → post-clean

Common command:

mvn clean

2️⃣ Default Lifecycle (Most Important for Selenium)

This lifecycle is used to compile code, run tests, and package the project.

Key Phases (Interview Focus)

PhasePurpose
validateChecks project structure
compileCompiles source code
testExecutes TestNG/JUnit tests
packageCreates JAR/WAR
verifyVerifies integration tests
installStores artifact in local repo
deployDeploys to remote repo

🔹 How lifecycle works (Very Important)

If you run:

mvn test

Maven automatically runs:

validate → compile → test

If you run:

mvn install

Maven runs:

validate → compile → test → package → verify → install

🔹 Selenium Example

mvn clean test

Steps executed:

  1. Deletes old target/

  2. Compiles code

  3. Executes Selenium + TestNG tests

  4. Generates reports


3️⃣ Site Lifecycle

Used to generate project documentation and reports.

Phases:

pre-site → site → post-site → site-deploy

Command:

mvn site


Quick Summary (Memorize)

  • mvn clean → removes old build

  • mvn test → runs Selenium tests

  • mvn install → saves build to local repo

  • Maven always executes previous phases automatically




Question: What is pom.xml and what are its key elements?
Answer: pom.xml (Project Object Model) is the core configuration file in Maven.

Important elements:

  • <dependencies> – To manage external libraries.

  • <build> – Custom build steps, plugins, test execution control.

  • <repositories> – Define external repo URLs (e.g., Nexus).

  • <properties> – Project-level config (e.g., Java version).

  • <profiles> – For managing different environments (dev, QA, prod).


Question: How do you manage dependencies in Maven?
Answer:Dependencies are declared inside the <dependencies> tag in pom.xml.

Example:


<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.19.0</version> </dependency>


Maven downloads these automatically from the central repository or a custom one


Question: What is the difference between compile, test, provided, and runtime scopes in Maven?
Answer: 
Scope Description
compile -- Default scope, available in all classpaths.
test -- Available only during testing.
provided -- Required for compile, but not at runtime (e.g., servlet API).
runtime -- Required only during execution, not compilation.

Question: How do you execute tests using Maven?
Answer:Use the Surefire plugin to run tests:

mvn clean test

To run a specific test suite:
mvn test -DsuiteXmlFile=testng.xml

Question: How can you skip test cases in Maven?
Answer:You can skip test execution using:

mvn install -DskipTests

This compiles tests but skips running them.

To skip compilation and execution:

mvn install -Dmaven.test.skip=true


Question: What is the difference between clean, install, validate, package, and verify?
Answer:
Command Description
clean -- Deletes target/ directory.
validate -- Checks project is correct and all needed info is available.
compile -- Compiles the source code.
test -- Runs tests using testing framework.
package -- Packages compiled code into a .jar or .war.
verify -- Runs checks on test results.
install -- Installs the package to local repo (~/.m2).

Question: How do you run TestNG XML using Maven?
Answer: 
<configuration>
    <suiteXmlFiles>
        <suiteXmlFile>testng.xml</suiteXmlFile>
    </suiteXmlFiles>
</configuration>


Question: How do you handle version conflicts in Maven?
Answer:Use the command:

mvn dependency:tree

This shows the dependency hierarchy and highlights conflicts. Use dependency management or exclusions to resolve them:

<exclusions>
  <exclusion>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
  </exclusion>
</exclusions>



Question: What is the Surefire plugin?
Answer:Apache Surefire is a Maven plugin used for executing unit and integration tests.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.2.5</version>
</plugin>

Question: How do you use profiles in Maven?
Answer:Profiles are used to run Maven builds for different environments:

<profiles>
  <profile>
    <id>qa</id>
    <properties>
      <env>qa</env>
    </properties>
  </profile>
</profiles>

Activate it with:
mvn test -P qa

Interview questions

ADOBE 

𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧: How do you handle dynamic web tables in test automation?

Hint: Use XPath or CSS selectors to locate table rows and columns dynamically. Loop through rows and columns to interact with or verify table data.

𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧: How do you find the longest palindromic substring in a given string?
Hint: Use dynamic programming or expand around the centre approach to identify the longest substring that reads the same forward and backward.

𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧: You have a lighter and two ropes. Each rope burns in 60 minutes but not evenly. How can you measure:
45 minutes?
50 minutes?

𝐀𝐧𝐬𝐰𝐞𝐫:
𝟒𝟓 𝐌𝐢𝐧𝐮𝐭𝐞𝐬: Light rope 1 at both ends and rope 2 at one end simultaneously. When rope 1 burns out (30 minutes), light the other end of rope 2 (15 minutes).

**try for 50 minutes

𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧: Given two strings s1 and s2, determine if s2 contains a permutation of s1. In other words, return true if one of s1's permutations is a substring of s2, or false otherwise.
input: s1 = "ab" s2 = "eidbaooo"
output: true

𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡:
Understand the Problem: We need to find if any permutation of s1 is a substring of s2.
Sliding Window Technique: Use a sliding window approach to compare segments of s2 with s1.

Question : What do you understand about beta testing? What are the different types of beta testing?
Answer: Genuine users of the software application undertake beta testing in a real environment. One type of User Acceptance Testing is beta testing. A small number of end-users of the product are given a beta version of the program in order to receive input on the product quality. Beta testing reduces the chances of a product failing and improves the product's quality by allowing customers to validate it.
Following are the different types of beta testing :

Traditional Beta testing: Traditional Beta testing is distributing the product to the target market and collecting all relevant data. This information can be used to improve the product.
Public Beta Testing: The product is made available to the general public via web channels, and data can be gathered from anyone. Product improvements can be made based on customer input. Microsoft, for example, undertook the largest of all Beta Tests for its operating system Windows 8 prior to its official release.
Technical Beta Testing: A product is delivered to a group of employees of a company and feedback/data is collected from the employees.
Focused Beta Testing: A software product is distributed to the public for the purpose of gathering input on specific program features. For instance, the software's most important features.
Post-release Beta Testing: After a software product is launched to the market, data is collected in order to improve the product for future releases.

Question : What do you understand about alpha testing? What are its objectives?
Answer: Alpha testing is a type of software testing that is used to find issues before a product is released to real users or the general public. One type of user acceptability testing is alpha testing. It is referred to as alpha testing since it is done early in the software development process, near the ending. Homestead software developers or quality assurance staff frequently undertake alpha testing. It's the final level of testing before the software is released into the real world.

Following are the objectives of alpha testing:

The goal of alpha testing is to improve the software product by identifying flaws that were missed in prior tests.
The goal of alpha testing is to improve the software product by identifying and addressing flaws that were missed during prior tests.
The goal of alpha testing is to bring customers into the development process as early as possible.
Alpha testing is used to gain a better understanding of the software's reliability during the early phases of development.


Question : What do you understand about Risk based testing?
Answer: Risk-based testing (RBT) is a method of software testing that is based on risk likelihood. It entails analyzing the risk based on software complexity, business criticality, frequency of use, and probable Defect areas, among other factors. Risk-based testing prioritizes testing of software programme aspects and functions that are more important and likely to have flaws.

Risk is the occurrence of an unknown event that has a positive or negative impact on a project's measured success criteria. It could be something that happened in the past, something that is happening now, or something that will happen in the future. These unforeseen events might have an impact on a project's cost, business, technical, and quality goals.

Risks can be positive or negative. Positive risks are referred to as opportunities, and they aid in the long-term viability of a corporation. Investing in a new project, changing corporate processes, and developing new products are just a few examples.

Negative risks are also known as threats, and strategies to reduce or eliminate them are necessary for project success.


Question : Differentiate between walkthrough and inspection.
Answer: 
Walkthrough - A walkthrough is a technique for doing a quick group or individual review. In a walkthrough, the author describes and explains his work product to his peers or supervisor in an informal gathering to receive comments. The legitimacy of the suggested work product solution is checked here. It is less expensive to make adjustments while the design is still on paper rather than during conversion. A walkthrough is a form of quality assurance that is done in a static manner.

Walkthrough vs Inspection
It is informal in nature.
It is formal in nature.

The developer starts it.
The project team starts it.

The developer of the product takes the lead throughout the walkthrough.
The inspection is conducted by a group of people from several departments. The tour is usually attended by members of the same project team.

The walkthrough does not employ a checklist.
A checklist is used to identify flaws.
Overview, little or no preparation, little or no preparation examination (real walkthrough meeting), rework, and follow up are all part of the walkthrough process.
Overview, preparation, inspection, rework, and follow-up are all part of the inspection process.

In the steps, there is no set protocol.
Each phase has a formalized protocol.

Because there is no specific checklist to evaluate the programme, the walkthrough takes less time.
An inspection takes longer since the checklist items are checked off one by one.

It is generally unplanned in nature.
Scheduled meeting with fixed duties allocated to all participants.

Because it is unmoderated, there is no moderator.
The responsibility of the moderator is to ensure that the talks stay on track.
reference - https://www.interviewbit.com/sdet-interview-questions/#walkthrough-vs-inspection -- to be deleted

Question : What do you understand about fuzz testing? What are the types of bugs detected by fuzz testing?
Answer: Fuzz Testing is a software testing technique that utilizes erroneous, unexpected, or random data as input and then looks for exceptions like crashes and memory leaks. It's a type of automated testing that's used to define system testing techniques that use a randomized or dispersed approach. During fuzz testing, a system or software program may have a variety of data input problems or glitches.

Following are the different phases of Fuzz Testing:





Question : 
Answer: 


Question : 
Answer: 


Question : 
Answer: 


popular posts