0% found this document useful (0 votes)
33 views149 pages

Selenium Interview Questions and Answers

The document provides a comprehensive overview of Selenium, detailing its core components such as Selenium IDE, WebDriver, and Grid, along with their functionalities. It also covers various topics including locators, waits, synchronization, and coding challenges, offering examples and best practices for effective automation testing. Additionally, it discusses limitations of Selenium and advanced concepts like handling dynamic elements and integrating JavaScript.

Uploaded by

hardeep dhawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views149 pages

Selenium Interview Questions and Answers

The document provides a comprehensive overview of Selenium, detailing its core components such as Selenium IDE, WebDriver, and Grid, along with their functionalities. It also covers various topics including locators, waits, synchronization, and coding challenges, offering examples and best practices for effective automation testing. Additionally, it discusses limitations of Selenium and advanced concepts like handling dynamic elements and integrating JavaScript.

Uploaded by

hardeep dhawan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1. What is Selenium and its core components?

Answer:
Selenium is an open-source suite for automating web browsers. It enables testers to write scripts in
multiple languages (Java, Python, C#, etc.) to simulate user actions and validate web applications.

Core components:

1. Selenium IDE – Browser plug-in to record + playback simple tests.

2. Selenium WebDriver – Core API for writing automation scripts programmatically.

3. Selenium Grid – Enables distributed execution across multiple machines/browsers.

4. (Legacy) Selenium RC – Older version replaced by WebDriver.

Example:

WebDriver driver = new ChromeDriver();

driver.get("https://example.com");

System.out.println(driver.getTitle());

driver.quit();

Interview Tip: Highlight that WebDriver provides direct OS-level communication with browsers,
unlike Selenium RC’s JavaScript injection.

Q2. Difference between Selenium IDE, RC, WebDriver and Grid

Answer:

Component Purpose Language Support Execution Mode

Selenium IDE Record & playback tool Limited (no coding) Manual playback in browser

Selenium RC Legacy server-based API Multi-language Runs via Selenium Server

Selenium WebDriver Core modern API Multi-language Direct browser control

Selenium Grid Parallel execution Uses WebDriver Distributed nodes

Tip: Say – “WebDriver + Grid are industry standards today; IDE is for quick demos only.”

Q3. What are the limitations of Selenium?

Answer:

 Works only for web applications, not desktop or mobile (without Appium).

 No built-in reporting mechanism.

 Cannot handle Captcha, OTP, or barcode validations directly.


 Requires external libraries for file upload/download or database testing.

Tip: When asked, mention how you overcame these using third-party tools (e.g., Robot class, Extent
Reports, JDBC).

Q4. Types of locators used in Selenium

Answer:
Locators tell Selenium which element to interact with.
Types include:

 ID

 Name

 Class Name

 Tag Name

 Link Text / Partial Link Text

 CSS Selector

 XPath

Example:

driver.findElement(By.id("username")).sendKeys("Deepika");

driver.findElement(By.cssSelector("input[type='password']")).sendKeys("pass123");

driver.findElement(By.xpath("//button[text()='Login']")).click();

Tip: Prefer ID for speed → CSS Selector → XPath (last resort when dynamic).

Q5. Difference between findElement() and findElements()

Answer:

 findElement() → Returns single WebElement; throws NoSuchElementException if not found.

 findElements() → Returns List <WebElement>; returns empty list if none found.

Example:

WebElement searchBox = driver.findElement(By.name("q"));

List<WebElement> links = driver.findElements(By.tagName("a"));

System.out.println("Total links: " + links.size());

Tip: Explain that findElements() is safer when element presence is optional.


Q6. Difference between driver.close() and driver.quit()

Answer:

 driver.close() closes the current browser tab/window where the WebDriver is focused.

 driver.quit() closes all browser windows and ends the entire WebDriver session.

Example:

driver.close(); // closes one tab

driver.quit(); // closes all tabs & ends session

Tip: Always use quit() in teardown (@AfterMethod) to free memory and avoid orphan ChromeDriver
processes.

Q7. What is Page Object Model (POM)?


Answer:
POM is a design pattern that creates an object repository for web elements.
It separates test logic from element locators, making scripts more maintainable.

Example:

// LoginPage.java

public class LoginPage {

WebDriver driver;

@FindBy(id="userEmail") WebElement email;

@FindBy(id="userPassword") WebElement password;

@FindBy(id="login") WebElement loginBtn;

public LoginPage(WebDriver driver){

this.driver = driver;

PageFactory.initElements(driver, this);

public void login(String user, String pass){

email.sendKeys(user);

password.sendKeys(pass);

loginBtn.click();

}
Tip: Mention that it reduces duplication and aligns with the Single Responsibility Principle.

Q8. How to handle dropdowns in Selenium

Answer:
Use the Select class to interact with <select> HTML elements.

Example:

WebElement countryDropdown = driver.findElement(By.id("country"));

Select select = new Select(countryDropdown);

select.selectByVisibleText("India");

select.selectByValue("IN");

select.selectByIndex(2);

Tip: For non-<select> dropdowns (custom HTML), use Actions class + click() or JavaScriptExecutor.

Q9. How to switch between frames and iframes

Answer:
Web pages may have nested <iframe> tags.
Use driver.switchTo().frame() and driver.switchTo().defaultContent().

Example:

driver.switchTo().frame("frameName");

driver.findElement(By.id("button")).click();

driver.switchTo().defaultContent(); // back to main page

Tip: You can switch by index, name, or WebElement. Always switch back after actions.

Q10. Handling alerts and JavaScript pop-ups

Answer:
Use the Alert interface to handle browser alerts.

Example:

Alert alert = driver.switchTo().alert();

System.out.println(alert.getText());

alert.accept(); // OK

// alert.dismiss(); // Cancel

Tip: For HTML pop-ups (not JS alerts), handle them as normal WebElements.
Q11. How do you capture screenshots in Selenium?

Answer:
Use the TakesScreenshot interface.

Example:

TakesScreenshot ts = (TakesScreenshot) driver;

File src = ts.getScreenshotAs(OutputType.FILE);

File dest = new File("screenshots/error.png");

FileUtils.copyFile(src, dest);

Tip: Integrate screenshot capture in failure listeners (ITestListener → onTestFailure).

Q12. How to perform mouse hover using Actions class

Answer:
The Actions class simulates advanced user gestures like hover, drag-drop, or double-click.

Example:

Actions act = new Actions(driver);

WebElement menu = driver.findElement(By.id("menu"));

act.moveToElement(menu).perform();

Tip: Always use perform() at the end to execute the built action chain.

Q13. What are different types of waits in Selenium?

Answer:
Waits synchronize the script with the browser’s speed.
Types:

 Implicit Wait – global; waits for element presence.

 Explicit Wait (WebDriverWait) – waits for specific condition.

 Fluent Wait – polls at intervals, ignores exceptions.

Example:

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("loginBtn")));
Tip: Prefer explicit waits for dynamic elements instead of large implicit waits.

Q14. Explain synchronization in Selenium

Answer:
Synchronization ensures Selenium commands execute only when the webpage and elements are
ready.
It avoids exceptions like ElementNotInteractableException or NoSuchElementException.

Example:

wait.until(ExpectedConditions.elementToBeClickable(loginBtn)).click();

Tip: Synchronization = using waits + proper page load strategies.

Q15. Difference between Implicit, Explicit and Fluent Wait

Answer:

Type Scope Customization Example

driver.manage().timeouts().implicitlyWait(10,
Implicit Global for driver session No
TimeUnit.SECONDS)

Specific
Explicit Yes WebDriverWait
element/condition

Same as Explicit + polling


Fluent Yes new FluentWait<>(driver)
& exception handling

Example:

FluentWait<WebDriver> wait = new FluentWait<>(driver)

.withTimeout(Duration.ofSeconds(20))

.pollingEvery(Duration.ofSeconds(2))

.ignoring(NoSuchElementException.class);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));

Tip: Use Fluent Wait for dynamic or slow-loading elements; combine it with ExpectedConditions for
robustness.

Section 2 – XPath, Locators & Dynamic Elements


Q16. What is XPath in Selenium?

Answer:
XPath (XML Path Language) is a syntax used to navigate through elements and attributes in an
XML/HTML document.
In Selenium, it’s mainly used to locate elements when id or name aren’t reliable.

Example:

WebElement loginBtn = driver.findElement(By.xpath("//button[@id='login']"));

Tip: XPath works both on HTML and XML DOM trees → great for dynamic pages.

Q17. Difference between Absolute and Relative XPath

Answer:

Type Syntax Description

Absolute XPath /html/body/div[2]/form/input Starts from root; brittle

Relative XPath //input[@id='username'] Starts from anywhere; more robust

Tip: Always use relative XPath; absolute breaks on small DOM changes.

Q18. How to handle Dynamic IDs in XPath

Answer:
Dynamic IDs often change with each reload (e.g., ctl00_main_123).
Use functions like contains(), starts-with(), ends-with().

Example:

driver.findElement(By.xpath("//input[contains(@id,'user')]"));

driver.findElement(By.xpath("//button[starts-with(@id,'login_')]"));

Tip: Combine text and partial attribute matches for stable locators.

Q19. What are XPath Axes?

Answer:
Axes let you traverse relationships between elements.

Axis Meaning Example

parent Selects parent node //input[@id='email']/parent::div

child Selects child nodes //div[@id='form']/child::input

following-sibling Next element on same level //label[text()='Email']/following-sibling::input


Axis Meaning Example

ancestor Moves upward //input[@id='pass']/ancestor::form

Tip: Demonstrating Axis use shows deep XPath mastery—rare skill in interviews.

Q20. Difference between XPath and CSS Selector

Answer:

Criteria XPath CSS Selector

Syntax XML-based CSS-based

Direction Both forward & backward Forward only

Text search Yes (text()) No direct text search

Readability More complex Simpler for static locators

Speed Slightly slower Slightly faster

Tip: Use CSS for simple static elements; XPath for dynamic and text-based search.

Q21. Write XPath using text() function

Answer:

driver.findElement(By.xpath("//a[text()='Login']"));

driver.findElement(By.xpath("//button[contains(text(),'Submit')]"));

Tip: text() is handy for buttons and links without unique IDs.

Q22. How to find element with multiple conditions in XPath

Answer:

driver.findElement(By.xpath("//input[@type='text' and @name='username']"));

driver.findElement(By.xpath("//button[@id='login' or @name='submit']"));

Tip: Use and / or operators to refine accuracy.

Q23. How to locate using index in XPath

Answer:

driver.findElement(By.xpath("(//input[@type='text'])[2]"));

Tip: Avoid index if possible—prefer unique attributes for stability.


Q24. How to traverse from child to parent element

Answer:

driver.findElement(By.xpath("//input[@id='email']/parent::div"));

Tip: Useful when only the child has known locators and parent needs interaction.

Q25. Locate element using normalize-space()

Answer:
normalize-space() ignores extra spaces in text content.

driver.findElement(By.xpath("//a[normalize-space()='Sign In']"));

Tip: Great for apps where developers use inconsistent spacing.

Q26. Write custom CSS Selectors

Answer:

driver.findElement(By.cssSelector("input[id='username']"));

driver.findElement(By.cssSelector("button[class*='submit']")); // contains

driver.findElement(By.cssSelector("div#loginForm input[type='text']"));

Tip: Use *= contains, ^= starts-with, $= ends-with for dynamic attributes.

Q27. Difference between contains() and starts-with() in XPath

Answer:

Function Purpose Example

Partial match
contains() //input[contains(@id,'user')]
anywhere

Match from //input[starts-


starts-with()
beginning with(@id,'user_')]

Tip: contains() is more flexible but can match


too much – be specific.

Q28. Handling lists and dynamic tables using XPath

Answer:

List<WebElement> rows = driver.findElements(By.xpath("//table[@id='data']/tbody/tr"));


for(WebElement row : rows){

System.out.println(row.getText());

Tip: Use dynamic XPath with loop index when validating grid data.

Q29. What is Shadow DOM and can XPath access it?

Answer:
Shadow DOM is a separate DOM tree inside elements (e.g., web components).
XPath cannot access Shadow DOM directly; you must use JavaScript Executor.

Example:

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow-host"));

WebElement shadowRoot = (WebElement) ((JavascriptExecutor)driver)

.executeScript("return arguments[0].shadowRoot", shadowHost);

shadowRoot.findElement(By.cssSelector("#innerButton")).click();

Tip: Mention Shadow DOM handling as a plus point – rarely known detail.

Q30. Best Practices for Robust Locators

Answer:

 Prefer id or name if static.

 Use meaningful XPath with functions (not indexes).

 Keep locators centralized (Page Object Model).

 Regularly validate after UI changes.

 Avoid absolute XPath.

Tip: End with this as a summary if the interviewer asks your “approach to locator strategy.”

Section 3 – Selenium Coding Challenges

Q31. How to open multiple browser windows and switch between them?

Answer:
When a new window or tab opens, Selenium can handle it using window handles.

Example:

String parent = driver.getWindowHandle();


driver.findElement(By.id("openTab")).click();

Set<String> handles = driver.getWindowHandles();

for (String handle : handles) {

driver.switchTo().window(handle);

System.out.println(driver.getTitle());

// Switch back

driver.switchTo().window(parent);

Tip: Stress that getWindowHandles() returns a Set, so always iterate to find the new window.

Q32. How to perform drag-and-drop?

Answer:
Use the Actions class for mouse operations.

Example:

WebElement src = driver.findElement(By.id("source"));

WebElement target = driver.findElement(By.id("target"));

Actions act = new Actions(driver);

act.dragAndDrop(src, target).perform();

Tip: Some HTML5 drag-drops fail with standard API; mention you can use JavaScriptExecutor
workaround.

Q33. How to handle file upload in Selenium?

Answer:
If the <input type="file"> element is present, send the file path directly.

Example:

driver.findElement(By.id("uploadFile")).sendKeys("/Users/deepika/Documents/sample.txt");

Tip: If upload uses a system dialog, use Robot class or AutoIt (Windows).

Q34. How to handle file download?


Answer:
Set browser preferences before initializing WebDriver.

Example (Chrome):

HashMap<String, Object> prefs = new HashMap<>();

prefs.put("download.default_directory", "/Users/deepika/Downloads");

ChromeOptions options = new ChromeOptions();

options.setExperimentalOption("prefs", prefs);

WebDriver driver = new ChromeDriver(options);

Tip: This is a key coding challenge — remember that Selenium doesn’t handle OS dialogs.

Q35. How to validate broken links on a webpage?

Answer:
Use HttpURLConnection to verify response codes of all anchor tags.

Example:

List<WebElement> links = driver.findElements(By.tagName("a"));

for (WebElement link : links) {

String url = link.getAttribute("href");

HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

conn.connect();

if (conn.getResponseCode() >= 400) {

System.out.println("Broken link: " + url);

Tip: Common interview favorite — shows understanding of Java + Selenium integration.

Q36. How to verify tooltip text of an element?

Answer:

String tooltip = driver.findElement(By.id("helpIcon")).getAttribute("title");

Assert.assertEquals(tooltip, "Expected tooltip text");

Tip: Tooltips are usually stored in the title attribute or as hidden divs.
Q37. How to scroll a webpage using Selenium?

Answer:
Use JavaScriptExecutor to scroll vertically or to specific elements.

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("window.scrollBy(0,500)");

WebElement footer = driver.findElement(By.id("footer"));

js.executeScript("arguments[0].scrollIntoView(true);", footer);

Tip: Great to mention when explaining hybrid use of Selenium + JavaScript.

Q38. How to perform right-click (context click)?

Answer:

Actions act = new Actions(driver);

WebElement button = driver.findElement(By.id("rightClick"));

act.contextClick(button).perform();

Tip: Combine with Keys.ARROW_DOWN and Keys.ENTER for selecting from context menus.

Q39. How to capture all links and print their text?

Answer:

List<WebElement> links = driver.findElements(By.tagName("a"));

for (WebElement link : links) {

System.out.println(link.getText() + " → " + link.getAttribute("href"));

Tip: Interviewers often tweak this to “print all links in the footer.”

Q40. How to check if an element is displayed, enabled, and selected?

Answer:

WebElement checkbox = driver.findElement(By.id("agree"));

System.out.println(checkbox.isDisplayed());

System.out.println(checkbox.isEnabled());
System.out.println(checkbox.isSelected());

Tip: Always combine isDisplayed() checks with waits to avoid false negatives.

Q41. How to handle dynamic web tables and fetch a cell value?

Answer:

WebElement cell = driver.findElement(

By.xpath("//table[@id='orders']/tbody/tr[3]/td[2]")

);

System.out.println(cell.getText());

Tip: For unknown row counts, loop through tr and td using nested loops.

Q42. How to validate sorting functionality in a table?

Answer:

List<WebElement> elements = driver.findElements(By.xpath("//table//tr/td[1]"));

List<String> original = elements.stream().map(WebElement::getText).collect(Collectors.toList());

List<String> sorted = new ArrayList<>(original);

Collections.sort(sorted);

Assert.assertEquals(original, sorted);

Tip: Stream API impresses interviewers—shows Java 8 proficiency.

Q43. How to capture text from hidden elements?

Answer:
Hidden elements can’t be accessed directly—use JavaScript.

JavascriptExecutor js = (JavascriptExecutor) driver;

String hiddenText = js.executeScript(

"return document.getElementById('hidden').textContent;"

).toString();

Tip: Great to mention as a workaround to ElementNotVisibleException.

Q44. How to handle stale element exceptions?


Answer:
Occurs when the DOM changes after locating an element.
Solution → re-locate element or use waits.

Example:

WebElement btn = driver.findElement(By.id("refresh"));

try {

btn.click();

} catch (StaleElementReferenceException e) {

btn = driver.findElement(By.id("refresh"));

btn.click();

Tip: Mention this under “Synchronization Challenges.”

Q45. How to highlight elements during test execution?

Answer:
Use JavaScript to temporarily change element style.

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;

WebElement element = driver.findElement(By.id("loginBtn"));

js.executeScript("arguments[0].style.border='3px solid red'", element);

Tip: It’s optional but useful for debugging visual validations.

Section 4 – Advanced Selenium Practices

Q46. What is JavaScriptExecutor in Selenium, and when do you use it?

Answer:
JavaScriptExecutor allows executing JavaScript directly in the browser through WebDriver.
It’s used when native Selenium methods fail (e.g., for hidden elements, scrolling, or modifying DOM
properties).

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript("arguments[0].click();", driver.findElement(By.id("submitBtn")));

Tip: Mention that you use it for hidden elements, performance measurements, or dynamic scrolling.

Q47. How to handle AJAX-based elements in Selenium?

Answer:
AJAX updates elements asynchronously without reloading the page.
Hence, use Explicit Waits to ensure elements are ready before interacting.

Example:

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

WebElement message = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ajaxMsg")));

System.out.println(message.getText());

Tip: Interviewers like when you mention “AJAX requires synchronization using WebDriverWait.”

Q48. How to run Selenium tests in Headless Mode?

Answer:
Headless browsers run tests without opening a visible UI — ideal for CI/CD pipelines.

Example (Chrome):

ChromeOptions options = new ChromeOptions();

options.addArguments("--headless", "--window-size=1920,1080");

WebDriver driver = new ChromeDriver(options);

driver.get("https://example.com");

Tip: Emphasize how headless mode saves execution time in Jenkins or GitHub Actions.

Q49. How to handle HTTPS/SSL certificate errors in Selenium?

Answer:
Use ChromeOptions or FirefoxOptions to accept insecure certificates.

Example:

ChromeOptions options = new ChromeOptions();

options.setAcceptInsecureCerts(true);

WebDriver driver = new ChromeDriver(options);

Tip: Mention that this is important when automating lower environments (QA/UAT) with self-signed
certificates.
Q50. How to perform Cross-Browser Testing in Selenium?

Answer:
Use WebDriver instances for different browsers (Chrome, Edge, Firefox, Safari).

Example:

WebDriver driver;

String browser = "firefox";

if(browser.equalsIgnoreCase("chrome"))

driver = new ChromeDriver();

else if(browser.equalsIgnoreCase("firefox"))

driver = new FirefoxDriver();

else

driver = new EdgeDriver();

Tip: Mention Selenium Grid or cloud services like BrowserStack for large-scale compatibility testing.

Q51. What is Selenium Grid and how do you use it?

Answer:
Selenium Grid allows parallel test execution across multiple browsers and machines.
It consists of:

 Hub: Central control point

 Nodes: Connected machines running tests

Example Setup Command:

java -jar selenium-server-4.9.0.jar hub

java -jar selenium-server-4.9.0.jar node --hub http://localhost:4444

Tip: Say you’ve used Grid to reduce test cycle time via parallelism.

Q52. How do you handle authentication pop-ups?

Answer:
Pass credentials directly in the URL.

Example:

driver.get("https://username:[email protected]/basic_auth");

Tip: For new browser versions (where this is blocked), use Robot Class or AutoIT.
Q53. How to add browser extensions in Selenium?

Answer:
Use ChromeOptions or FirefoxProfile.

Example:

ChromeOptions options = new ChromeOptions();

options.addExtensions(new File("/Users/deepika/Downloads/adblock.crx"));

WebDriver driver = new ChromeDriver(options);

Tip: Useful in testing environments requiring plugin configurations.

Q54. How to manage cookies in Selenium?


Answer:
You can add, get, and delete cookies.

Example:

Cookie cookie = new Cookie("user", "Deepika");

driver.manage().addCookie(cookie);

System.out.println(driver.manage().getCookies());

driver.manage().deleteAllCookies();

Tip: Common in session management and login persistence scenarios.

Q55. How to capture browser console logs?

Answer:
Use LogEntries and LogType.BROWSER.

Example:

LogEntries logs = driver.manage().logs().get(LogType.BROWSER);

for (LogEntry entry : logs) {

System.out.println(entry.getMessage());

Tip: Mention it helps debug front-end errors during test execution.

Q56. What are DesiredCapabilities and how are they used?


Answer:
DesiredCapabilities were used (pre-Selenium 4) to set properties like browser name, version, and
platform.
In Selenium 4, these are replaced by browser-specific Options classes (e.g., ChromeOptions).

Example (Legacy):

DesiredCapabilities caps = new DesiredCapabilities();

caps.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

Tip: Explain the migration to Options (ChromeOptions, FirefoxOptions) in Selenium 4+.

Q57. How to handle browser notifications and pop-ups?

Answer:
Disable browser notifications using ChromeOptions.

Example:

ChromeOptions options = new ChromeOptions();

options.addArguments("--disable-notifications");

WebDriver driver = new ChromeDriver(options);

Tip: Useful for e-commerce or social media apps where notification pop-ups interrupt test flow.

Q58. How to maximize test stability in Selenium?

Answer:

 Use Explicit waits instead of Thread.sleep()

 Implement retry logic for flaky tests

 Use PageFactory or Page Object Model

 Keep independent test data

 Run in stable environments (disable pop-ups, ads)

Tip: Explain that automation reliability > 90% is achieved by solid waits + clean locators.

Q59. How to execute tests in parallel using TestNG?

Answer:
Use the parallel attribute in testng.xml.

Example:

<suite name="ParallelTests" parallel="tests" thread-count="2">

<test name="ChromeTest">
<parameter name="browser" value="chrome"/>

<classes><class name="tests.LoginTest"/></classes>

</test>

<test name="EdgeTest">

<parameter name="browser" value="edge"/>

<classes><class name="tests.LoginTest"/></classes>

</test>

</suite>

Tip: Say that parallel execution improves efficiency by up to 50% in regression runs.

Q60. How to take full-page screenshots in Selenium 4?

Answer:
Selenium 4 introduced the getFullPageScreenshotAs() method (for Firefox and Chrome).

Example:

FirefoxDriver driver = new FirefoxDriver();

File src = driver.getFullPageScreenshotAs(OutputType.FILE);

FileUtils.copyFile(src, new File("fullpage.png"));

Tip: A great example to show your awareness of Selenium 4 enhancements.

Section 4 – Advanced Selenium Practices Completed!

Now you have Sections 1–4 (Q1–Q60) fully ready:

 Selenium Fundamentals

 XPath & Locators

 Coding Challenges

 Advanced Selenium Practices

Section 5 – Core Java Concepts for Automation


Q61. What are the main OOPs principles in Java and why are they important in test automation?

Detailed Answer — Concept & Why it matters

Object-Oriented Programming (OOP) is a programming paradigm that models software as a


collection of objects that combine state (fields) and behaviour (methods). The four main principles
are encapsulation, abstraction, inheritance, and polymorphism. In test automation these principles
let you design frameworks that are modular, maintainable, and extensible — which is essential for
large test suites.

 Encapsulation: Hiding internal state and exposing behavior through public methods.
In test automation: Page Objects encapsulate locators and low-level interactions; tests call
high-level methods (e.g., loginPage.login(user, pass)), preventing tests from depending on
internal locator changes.

 Abstraction: Presenting only essential information and hiding implementation complexity.


In test automation: A TestBase class can abstract browser setup/teardown, config reading, or
WebDriver initialization so test classes don't need to handle those details.

 Inheritance: One class inherits fields and methods from another.


In test automation: LoginTest extends TestBase reuses setup code. Also useful for creating
specialized page classes that extend generic page behaviors.

 Polymorphism: The ability for different classes to be treated as the same type.
In test automation: You can write methods to accept WebDriver interface or an abstract
Browser type. Also used when different page implementations provide a common interface.

Practical Example (POM + TestBase):

public class TestBase {

protected WebDriver driver;

public void initDriver(String browser) {

// read config and initialize ChromeDriver/FirefoxDriver

public void tearDown() {

if (driver != null) driver.quit();

public class LoginPage {

private WebDriver driver;

@FindBy(id="username") private WebElement username;

// constructor + methods

public void login(String user, String pass) {


username.sendKeys(user);

// ...

public class LoginTest extends TestBase {

@BeforeMethod

public void setup() {

initDriver("chrome");

@Test

public void userCanLogin() {

LoginPage lp = new LoginPage(driver);

lp.login("user","pass");

Common Pitfalls

 Overusing inheritance instead of composition — leads to rigid designs.

 Exposing WebElements as public (breaks encapsulation).

 Putting assertions inside page objects (they should be in tests).

Interview Talking Points

 Explain how OOP makes tests maintainable and how you used POM (a practical example).

 Mention tradeoffs: abstraction is great, but over-abstraction can hide what's being tested.

Q62. What is the difference between method overloading and overriding?

Detailed Answer — Definitions and Use-cases

 Method Overloading (compile-time polymorphism): Multiple methods in the same class


with the same name but different parameter lists (different type, number, or order of
parameters). The compiler decides which method to call at compile time based on argument
types.
Use-case in automation: Utility methods that accept different inputs — e.g.,
findElement(String locator) and findElement(By locator).
 Method Overriding (runtime polymorphism): A subclass provides a specific implementation
of a method already defined in its superclass. The decision of which method to call is at
runtime based on the object instance.
Use-case in automation: You might have BaseDriver with startBrowser() and a subclass
RemoteDriver that overrides it for Selenium Grid.

Examples

// Overloading

public void click(String css) { ... }

public void click(By by) { ... }

// Overriding

class BaseTest {

public void setup() { System.out.println("Base setup"); }

class MyTest extends BaseTest {

@Override

public void setup() { System.out.println("Custom setup"); }

Pitfalls

 Overloading can lead to ambiguous method signatures if not designed carefully.

 Overriding — remember to use @Override so the compiler helps catch mismatches.

Interview Tip

 Give a concrete example from your framework where you used overloading for convenience
and overriding to customize behavior.

Q63. Explain access modifiers in Java.

Detailed Answer — What, Where, Why

Java has four access levels for classes, methods, and variables:

1. public — accessible from any other class everywhere.

2. protected — accessible within the same package and subclasses (even if in different
packages).

3. default (package-private) — no modifier; accessible only within the same package.

4. private — accessible only within the declaring class.


Why this matters for automation

 Keep locators (WebElement) private to prevent tests from manipulating elements directly —
expose meaningful actions through public methods in page classes.

 Use protected for fields/methods you want subclasses (like specific test classes) to access but
not outsiders.

 Use package-private for helper classes that are framework-internal.

Example

public class LoginPage {

private WebDriver driver;

private WebElement username; // private - encapsulated

protected void waitForPage() { // protected - used by subclasses

// ...

public void login(String u, String p) { // public API for tests

// ...

Interview Talking Point

 Emphasize how you enforce encapsulation and why it helps minimize test breakage when UI
changes.

Q64. What is the difference between final, finally, and finalize()?

Detailed Answer & Clarification

 final (keyword)

o Applied to variables, methods, or classes.

o Final variable: value cannot be changed after initialization—useful for constants (final
String BASE_URL = "...").

o Final method: cannot be overridden.

o Final class: cannot be subclassed (e.g., java.lang.String is final).

 finally (block)

o A block used with try-catch that always executes whether an exception occurs or not
(unless JVM exits). Use it to release resources (files, DB connections). In test
automation, finally can ensure cleanup, but prefer test framework tearDown
methods.

 finalize() (method)

o A method that the garbage collector may call before collecting an object. Deprecated
and unreliable — don't rely on it. Use explicit resource management instead (try-
with-resources or explicit close()).

Example

final int MAX = 5;

try {

// some code

} catch(Exception e) {

// handle

} finally {

// cleanup

Pitfalls

 Don’t use finalize() for essential cleanup; it’s non-deterministic. Use try-with-resources for
streams or @After teardown.

Interview Tip

 Mention best practices: use final for constants and immutable references; use finally
sparingly and rely on TestNG/JUnit teardown for predictable cleanup.

Q65. How does exception handling work in Java?

Detailed Answer — Mechanism & Best Practices

Java exception handling uses try, catch, finally, and throw/throws. Exceptions are objects derived
from Throwable. There are two categories:

 Checked exceptions — must be declared or handled (e.g., IOException).

 Unchecked exceptions (RuntimeException) — optional to handle (e.g.,


NullPointerException).

Pattern in automation

 Use targeted catches (e.g., NoSuchElementException) when you have a fallback strategy like
retries.

 Don’t swallow exceptions. Log them with stack traces or rethrow to fail the test if
appropriate.
 Prefer more specific exceptions rather than catch (Exception e).

Example (retry pattern)

public void clickWithRetry(By by) {

int attempts = 0;

while(attempts < 2) {

try {

driver.findElement(by).click();

break;

} catch (StaleElementReferenceException e) {

attempts++;

Pitfalls

 Using Thread.sleep() instead of proper waits causes flakiness.

 Catching and ignoring exceptions will hide failures.

Interview Tip

 Explain how you handle expected transient exceptions (stale elements) gracefully and when
you let tests fail fast.

Q66. What is the difference between throw and throws?

Detailed Answer & Example

 throw: used inside a method to explicitly throw an exception instance.

 if (file == null) throw new IOException("File missing");

 throws: used in a method signature to declare that the method might throw certain checked
exceptions to the caller.

 public void readFile() throws IOException { ... }

When to use which

 Use throw when you detect an error condition and want to signal it immediately.

 Use throws when a method calls code that might cause a checked exception and you don’t
want to handle it there.

Automation example
 Methods that read config files can declare throws IOException and the test runner can
handle/report it.

Pitfalls

 Don’t overuse throws to avoid handling errors — declare exceptions when the caller needs
to manage them.

Interview Tip

 Show you understand exception propagation and how it affects test flow.

Q67. What are Collections in Java and why are they used in Selenium?

Detailed Answer

Java Collections Framework provides reusable data structures: List, Set, Queue, Map, etc. They
simplify storing, iterating and manipulating groups of objects. In Selenium, Collections are used to
store lists of WebElements, capture text, compare data sets, and assert ordered/unordered results.

Common Uses in Automation

 Store all products on a page to validate sorting or filtering.

 Keep a set of unique values (e.g., product IDs).

 Use Map<String,String> to map test data keys to values.

Example — Extracting product names

List<WebElement> elems = driver.findElements(By.cssSelector(".product-title"));

List<String> names = elems.stream().map(WebElement::getText).collect(Collectors.toList());

Tips

 Use List when order matters; Set when uniqueness matters.

 Streams + collectors make transformations concise and readable.

Pitfalls

 Be cautious when comparing Lists — leading/trailing whitespace or casing can cause


mismatches; normalize strings first.

Interview Tip

 Demonstrate using Map for parameterized test data or List to verify UI tables.

Q68. Difference between List, Set, and Map

Detailed Answer & Practical Advice

 List

o Ordered collection (maintains insertion order).


o Allows duplicates.

o Common implementations: ArrayList, LinkedList.

o Use-case: ordered search results, rows in a table.

 Set

o No duplicates allowed.

o No guaranteed ordering for HashSet; LinkedHashSet preserves insertion order;


TreeSet sorts.

o Use-case: unique identifiers, de-duplicating scraped values.

 Map

o Key-value pairs; keys unique.

o Implementations: HashMap (unsorted), LinkedHashMap, TreeMap.

o Use-case: config key-value pairs, storing element locators by name.

Example

List<String> list = new ArrayList<>();

Set<String> set = new HashSet<>();

Map<String, String> map = new HashMap<>();

map.put("username", "deepika");

Interview Tip

 Explain real examples: using Map to hold row->expectedValue mapping for validation.

Q69. How do you read and write data from files in Java?

Detailed Answer — Recommended Approaches

Test frameworks often need to read configuration, credentials, or test data. There are multiple APIs:

 Properties files — for key-value config.

 Properties prop = new Properties();

 try (FileInputStream fis = new FileInputStream("config.properties")) {

 prop.load(fis);

 }

 String url = prop.getProperty("baseUrl");

 Plain text — BufferedReader or Files.readAllLines.

 List<String> lines = Files.readAllLines(Paths.get("data.txt"));


 CSV — use Apache Commons CSV or OpenCSV for tabular test data.

 Excel — Apache POI for .xls/.xlsx files (common in enterprise frameworks).

Best Practices

 Encapsulate file IO in utility classes and close streams using try-with-resources.

 Keep credentials secure (not plain text in code or repo); use environment variables or secret
stores.

Pitfalls

 Hardcoding absolute paths — prefer project-relative or config-driven paths.

 Not closing streams — leads to resource leaks.

Interview Tip

 Show you know which format you chose and why (CSV for simple data, Excel if stakeholders
prefer spreadsheets).

Q70. What is the use of static keyword?

Detailed Answer & Common Uses in Frameworks

static binds a variable or method to the class, not to instances. Useful for:

 Constants: public static final String BASE_URL = "...";

 Utility methods: public static void takeScreenshot().

 Shared singletons or caches (use carefully in multi-threaded runs).

Example

public class Config {

public static final String BASE_URL = "https://example.com";

Pitfalls

 Overusing static for stateful objects (like WebDriver) can cause concurrency issues in parallel
runs. Prefer instance-level drivers or thread-local storage.

Interview Tip

 If parallel test execution is in scope, mention ThreadLocal<WebDriver> as an approach to


avoid static driver conflicts.

Q71. What is immutability in Java?

Detailed Explanation & Benefits


An immutable object cannot change once created. String is the classic example. Immutability helps
make code safer in multi-threaded contexts and prevents unintended side effects.

Example with String

String a = "hello";

String b = a.concat(" world");

System.out.println(a); // still "hello"

In Frameworks

 Use immutable configuration objects for test run parameters.

 Keep expected values immutable to avoid accidental modification in tests.

Pitfalls

 Overuse of immutability where mutability is expected can increase object creation overhead.
Use judiciously.

Interview Tip

 Explain when you choose immutable vs mutable structures (thread-safety vs performance


tradeoff).

Q72. What is the difference between == and .equals() in Java?

Detailed Explanation & Example

 == compares references (whether two variables point to the same object in memory).

 .equals() compares object content/value (depends on the class’s implementation).

Example

String s1 = new String("test");

String s2 = new String("test");

System.out.println(s1 == s2); // false (different objects)

System.out.println(s1.equals(s2)); // true (same content)

In Automation Assertions

 Always use .equals() (or Assert.assertEquals()) to check content equality. Using == on strings
or wrapper objects will lead to subtle bugs.

Interview Tip

 Show you understand that for custom objects, you must override equals() and hashCode()
correctly when used in collections or comparisons.

Q73. How do you use StringBuilder and StringBuffer?


Detailed Explanation & When to Use

 StringBuilder: mutable, non-synchronized — good for single-threaded contexts.

 StringBuffer: synchronized (thread-safe) — slower due to synchronization overhead.

Use-case in Automation

 Build long strings (e.g., building an HTML report), constructing large log messages, or
dynamically building XPath strings in loops.

Example

StringBuilder sb = new StringBuilder();

sb.append("Name: ").append(username).append(", Score: ").append(score);

String result = sb.toString();

Pitfalls

 Avoid many string concatenations in loops with +; use StringBuilder to improve performance.

Interview Tip

 Mention you prefer StringBuilder unless thread-safety is explicitly needed.

Q74. What are Lambda expressions in Java 8?

Detailed Explanation & Practical Value

Lambda expressions provide a concise way to represent an anonymous function (a block of code)
that can be passed around. They reduce boilerplate and are commonly used with Java Streams API
for functional-style data processing.

Example (Selenium)

List<WebElement> cards = driver.findElements(By.cssSelector(".card"));

cards.forEach(card -> System.out.println(card.getText()));

Benefits

 Cleaner, shorter code.

 Easier manipulation of collections with map, filter, collect.

Pitfalls

 Overly complex lambda expressions can be harder to debug; prefer clear, small lambdas.

Interview Tip

 Demonstrate one use-case where a lambda reduced several lines of imperative code into a
succinct operation (e.g., filtering elements).
Q75. How do you use Streams in Java 8 for Selenium automation?

Detailed Explanation & Examples

Streams let you chain transformations on collections concisely.

Example — Extract product names starting with 'A'

List<String> names = driver.findElements(By.cssSelector(".product .name"))

.stream()

.map(WebElement::getText)

.map(String::trim)

.filter(s -> s.startsWith("A"))

.collect(Collectors.toList());

Common Operations

 map — transform elements

 filter — select elements that satisfy a predicate

 collect — assemble results (e.g., toList(), toSet())

Benefits in automation

 Clean extraction and transformation of UI data for assertions or logs.

 Easy comparison between UI data and API-provided datasets.

Pitfalls

 Streams can be less readable for complex logic; break into steps or use helper methods.

Interview Tip

 Mention that streams simplified a data validation scenario (e.g., comparing API response list
with UI list).

Q76. Difference between Array and ArrayList

Detailed Explanation

 Array

o Fixed size; can store primitives and objects; direct indexing is fast.

o Use when number of elements is known and unchanging.

 ArrayList

o Dynamic, resizable array implementation from Collections framework; only stores


objects.

o Provides convenience methods (add, remove, contains), integrates with streams.


Example

String[] arr = new String[5]; // fixed

List<String> list = new ArrayList<>(); // dynamic

list.add("one");

Interview Tip

 Explain why you use ArrayList to store WebElement results (dynamic and integrated with
Streams).

Q77. What is an interface and how is it used in automation?

Detailed Explanation & Benefits

An interface is a contract specifying method signatures without implementation (Java 8 added


default methods). In automation frameworks, interfaces define behavior (e.g., a BrowserFactory
interface) that can have different implementations — local Chrome/Firefox or remote Grid drivers.
This promotes loose coupling and easier swapping of implementations.

Example

public interface Browser {

WebDriver createDriver();

public class ChromeBrowser implements Browser {

public WebDriver createDriver() {

return new ChromeDriver();

Benefits

 Easier to mock dependencies in unit tests.

 Swappable implementations for different environments.

Interview Tip

 Give an example where you used an interface to support local and remote drivers (or to
decouple logging/reporting implementations).

Q78. What is the difference between abstract class and interface?

Detailed Explanation & Use-cases

 Abstract class
o Can have state (fields) and implemented methods.

o Useful when classes share a common base implementation.

o Single inheritance (a class can extend only one abstract class).

 Interface

o Defines a contract; before Java 8, could only have abstract methods. Now supports
default and static methods.

o Supports multiple interface implementations (a class can implement many


interfaces).

When to use

 Use abstract classes for BaseTest where you provide common setup with fields.

 Use interfaces for capabilities (e.g., Loggable, Retryable) that many unrelated classes might
implement.

Interview Tip
 Show you choose the right tool: BaseTest as abstract class (shared code), and IDriverFactory
as an interface for pluggable drivers.

Q79. What is synchronization in Java?

Detailed Explanation & Context

Synchronization controls access to shared resources by multiple threads to prevent race conditions.
In automation, synchronization matters when running tests in parallel threads (TestNG parallel
execution). Without proper synchronization, shared data (logs, singletons) can get corrupted.

Example

public synchronized void writeLog(String message) {

// thread-safe logging

Alternatives
 Use ConcurrentHashMap, ThreadLocal (e.g., ThreadLocal<WebDriver>) to isolate driver per
thread.

 Use dedicated logging libraries which handle concurrency.

Pitfalls

 Overuse of synchronized can cause contention and slow parallel runs.

Interview Tip
 Demonstrate you used ThreadLocal<WebDriver> or other thread-safe patterns to enable
parallel test execution.
Q80. How do you handle properties/config files in Java automation frameworks?

Detailed Answer — Best Practices & Example

Why externalize config?

 Allows running the same code against different environments (dev/qa/prod) without code
changes.

 Keeps secrets/config separate (use secure storage for sensitive data).

Common approach

 Store environment-specific settings in config.properties.

 Load them at framework startup using Properties class, or better, use a configuration utility
that supports environment overrides.

Example

public class ConfigReader {

private Properties prop = new Properties();

public ConfigReader(String env) {

String file = env.equals("prod") ? "config-prod.properties" : "config.properties";

try (FileInputStream fis = new FileInputStream(file)) {

prop.load(fis);

public String getUrl() { return prop.getProperty("url"); }

Enhancements

 Use environment variables for sensitive data or CI secret stores.

 Support CLI args or system properties (e.g., -Denvironment=qa) to switch environments in CI.

Pitfalls

 Don’t commit secrets to source control.

 Avoid hard-coded file paths — use project-relative paths.

Interview Tip

 Describe how your runner reads a -Denv=qa system property and picks the right properties
file for the test run.
Section 6 – TestNG Framework (Q81–Q100)

Q81. What is TestNG, and why do we use it in automation testing?

Detailed Explanation:
TestNG (Test Next Generation) is a Java-based testing framework inspired by JUnit and NUnit but
designed to make automated testing more powerful and flexible. It provides annotations, grouping,
parameterization, parallel execution, and advanced reporting — all crucial for managing large
Selenium test suites.

Key Benefits:

 Organizes tests with annotations like @BeforeMethod, @Test, @AfterMethod.

 Supports data-driven testing (@DataProvider).

 Allows grouping and prioritizing tests.

 Enables parallel execution for faster CI runs.

 Generates HTML/XML reports automatically.

 Integrates with Maven, Jenkins, and other CI/CD tools.

Example:

public class LoginTest {

@BeforeMethod

public void setup() {

System.out.println("Launch Browser and open application");

@Test

public void validLoginTest() {

System.out.println("Login with valid credentials");

@AfterMethod

public void tearDown() {

System.out.println("Close browser");
}

Output Order:

@BeforeMethod → @Test → @AfterMethod

Why it’s important in automation:


TestNG standardizes test structure, improves maintainability, and integrates naturally with Selenium.

Interview Tip:
Be ready to explain how TestNG helped you structure tests, manage dependencies, and generate test
reports automatically in your current project.

Q82. What are TestNG annotations, and why are they useful?

Detailed Explanation:
Annotations in TestNG control test execution flow. Each annotation tells TestNG when and how to
execute a method in the lifecycle.

Common Annotations and Purpose:

Annotation Purpose

@BeforeSuite Runs once before the entire suite starts.

@BeforeTest Runs before <test> tag in XML.

@BeforeClass Runs once before all methods in a class.

@BeforeMethod Runs before each @Test method.

@Test Marks a method as a test case.

@AfterMethod Runs after each test method.

@AfterClass Runs once after all test methods in a class.

@AfterSuite Runs once after the entire suite completes.

Example:

@BeforeSuite

public void beforeSuite() { System.out.println("Before Suite"); }

@BeforeTest

public void beforeTest() { System.out.println("Before Test"); }


@BeforeClass

public void beforeClass() { System.out.println("Before Class"); }

@BeforeMethod

public void beforeMethod() { System.out.println("Before Method"); }

@Test

public void testCase() { System.out.println("Test Executed"); }

@AfterMethod

public void afterMethod() { System.out.println("After Method"); }

Interview Tip:
Mention you understand execution order — it’s a frequent practical interview question.

Q83. What is the difference between @BeforeMethod and @BeforeClass?

Detailed Explanation:

 @BeforeMethod: Runs before each test method.


→ Used to initialize browser, login, or reset test state.

 @BeforeClass: Runs once before all test methods in the class.


→ Used for one-time setup like connecting to DB or reading config.

Example:

@BeforeClass

public void launchBrowser() {

driver = new ChromeDriver();

@BeforeMethod

public void navigateToApp() {

driver.get("https://app.example.com");

Interview Tip:
Explain how using @BeforeClass avoids browser relaunch for every test (saves time).
Q84. How can you prioritize test cases in TestNG?

Detailed Explanation:
By using the priority attribute in the @Test annotation.

Example:

@Test(priority=1)

public void loginTest() {}

@Test(priority=2)

public void addProductTest() {}

@Test(priority=3)

public void logoutTest() {}

Default behavior:
If priority isn’t defined, TestNG runs tests in alphabetical order of method names.

Pitfalls:

 Priorities are optional but help control dependent test flow.

 Avoid relying solely on priority; prefer dependsOnMethods.

Interview Tip:
State that you use dependsOnMethods for true functional dependencies (e.g., checkout depends on
login).

Q85. What is the use of dependsOnMethods and dependsOnGroups?

Detailed Explanation:
These attributes define test dependencies — when a test should only run if another test/group
passes.

Example — Method dependency:

@Test

public void login() { ... }

@Test(dependsOnMethods={"login"})

public void purchase() { ... }

Example — Group dependency:


@Test(groups={"smoke"})

public void login() { ... }

@Test(dependsOnGroups={"smoke"})

public void verifyDashboard() { ... }

Pitfall:
If a dependent test fails, the next test is skipped (not failed).

Interview Tip:
Mention you use dependencies to maintain business flow integrity without manual sequencing.

Q86. How do you group test cases in TestNG?

Detailed Explanation:
Groups let you organize and run related tests (e.g., smoke, regression, sanity).

Example:

@Test(groups={"smoke"})

public void loginTest() {}

@Test(groups={"regression"})

public void addProductTest() {}

In testng.xml:

<groups>

<run>

<include name="smoke"/>

</run>

</groups>

Benefits:

 Selectively run subsets of tests.

 Integrates perfectly with CI pipelines (e.g., run only “smoke” on commits).

Interview Tip:
Mention grouping is part of your test suite management strategy — e.g., smoke tests before full
regression.

Q87. What is the use of @DataProvider in TestNG?


Detailed Explanation:
@DataProvider enables data-driven testing by passing multiple sets of data to a single test method.

Example:

@DataProvider(name="loginData")

public Object[][] getData() {

return new Object[][] {

{"user1","pass1"},

{"user2","pass2"}

};

@Test(dataProvider="loginData")

public void loginTest(String user, String pass) {

System.out.println(user + " | " + pass);

Why it’s powerful:

 Eliminates duplicate test code.

 Integrates easily with Excel or CSV file readers.

Interview Tip:
Explain how you used DataProvider to test multiple credential sets or form inputs dynamically.

Q88. How do you parameterize tests using TestNG XML?

Detailed Explanation:
You can define parameters in the testng.xml file and fetch them using @Parameters.

Example:

<parameter name="browser" value="chrome"/>

@Parameters("browser")

@Test

public void launchApp(String browser) {

if(browser.equals("chrome")) driver = new ChromeDriver();

Difference between @DataProvider and @Parameters:


@DataProvider @Parameters

Used for multiple data sets Used for single parameter values

Defined in code Defined in XML

Supports complex objects Supports only simple values

Interview Tip:
Mention that you use @Parameters for environment or browser parameters, and @DataProvider for
test data.

Q89. How do you disable a test case in TestNG?

Detailed Explanation:
Use the enabled=false attribute in the @Test annotation.

Example:

@Test(enabled=false)

public void underDevelopmentTest() {

// not executed

Alternate: Use @Ignore annotation or comment out temporarily.

Interview Tip:
Explain you disable tests temporarily for unstable or environment-dependent cases (not delete).

Q90. What is testng.xml and why is it important?

Detailed Explanation:
testng.xml is the suite configuration file that controls which tests, classes, and groups are executed.
It defines suite-level structure and parameters.

Example:

<suite name="Regression Suite" parallel="tests">

<test name="Login Module">

<classes>

<class name="tests.LoginTest"/>

<class name="tests.DashboardTest"/>

</classes>

</test>
</suite>

Why it’s important:

 Central control for execution.

 Enables grouping, parameterization, parallelism.

 Integrates with CI/CD pipelines easily.

Interview Tip:
Show you can create dynamic test suites and run parallel tests using XML configuration.

Q91. How do you execute tests in parallel using TestNG?

Detailed Explanation:
Parallel execution reduces total test time and can run on multiple browsers/environments.

Example — Parallel by methods:

<suite name="ParallelTests" parallel="methods" thread-count="3">

<test name="SmokeTests">

<classes>

<class name="tests.LoginTest"/>

</classes>

</test>

</suite>

Values for parallel:

 tests, classes, methods, instances.

Pitfalls:

 WebDriver objects must be thread-safe (use ThreadLocal<WebDriver>).

 Avoid sharing mutable state.

Interview Tip:
Mention you implemented parallelism using ThreadLocal drivers to run tests safely across multiple
threads.

Q92. What is soft assertion vs hard assertion?

Detailed Explanation:

 Hard Assertion (Assert): Fails the test immediately when an assertion fails.

 Soft Assertion (SoftAssert): Collects all failures and reports them after all checks.
Example:

SoftAssert soft = new SoftAssert();

soft.assertTrue(isLoggedIn);

soft.assertEquals(actualTitle, "Dashboard");

soft.assertAll(); // must call to report

Use-case:
Soft assertions are great for verifying multiple UI elements in one test.

Interview Tip:
Explain that you use SoftAssert when multiple independent checks exist in a single test.

Q93. What are listeners in TestNG?

Detailed Explanation:
Listeners are interfaces that let you customize test behavior and reporting by listening to TestNG
events like test start, pass, or fail.

Common Listeners:

 ITestListener

 ISuiteListener

 IInvokedMethodListener

Example (Screenshot on Failure):

public class Listeners extends BaseTest implements ITestListener {

public void onTestFailure(ITestResult result) {

takeScreenshot(result.getName());

Register in XML:

<listeners>

<listener class-name="utilities.Listeners"/>

</listeners>

Interview Tip:
Mention you integrated screenshot capture and extent reporting using listeners.

Q94. How to rerun failed tests in TestNG?


Detailed Explanation:
Use TestNG IRetryAnalyzer to automatically retry failed tests.

Example:

public class RetryAnalyzer implements IRetryAnalyzer {

int count = 0;

public boolean retry(ITestResult result) {

if (count < 2) {

count++;

return true;

return false;

Attach it to test:

@Test(retryAnalyzer=RetryAnalyzer.class)

public void flakyTest() { ... }

Interview Tip:
Say you used retry logic to handle flaky tests caused by temporary network/UI delays.

Q95. How can you run a specific group of tests from command line or Jenkins?

Command Line Example:

mvn test -Dgroups=smoke

Jenkins Integration:

 Pass -Dgroups=smoke as build parameter in Maven Goals.

 Or define environment variable to choose test groups dynamically.

Interview Tip:
Explain you parameterized test group execution in Jenkins to save CI time.

Q96. How can you generate custom HTML reports in TestNG?

Detailed Explanation:
TestNG generates default HTML reports, but for better visuals, integrate ExtentReports or Allure.

Example (ExtentReport Integration):


ExtentReports extent = new ExtentReports();

ExtentTest test = extent.createTest("LoginTest");

test.log(Status.PASS, "Login successful");

extent.flush();

Interview Tip:
Show you integrated ExtentReports and attached screenshots for failures automatically.

Q97. How do you skip a test in TestNG?

Example:

@Test

public void testSkip() {

throw new SkipException("Skipping this test due to environment issue");

Interview Tip:
Explain skipping is better than failing when the environment is not ready or dependent data is
missing.

Q98. How do you share data between test methods?

Detailed Explanation:
Use class variables, or store data in a Map, or use dependency (dependsOnMethods).

Example:

String orderId;

@Test

public void createOrder() { orderId = "12345"; }

@Test(dependsOnMethods="createOrder")

public void verifyOrder() { System.out.println(orderId); }

Interview Tip:
Explain you use such dependencies to maintain state across related tests logically.

Q99. What is factory in TestNG?


Detailed Explanation:
@Factory allows running a test class multiple times with different data sets — creating separate
instances.

Example:

public class LoginTest {

private String username;

public LoginTest(String username) { this.username = username; }

@Test

public void testLogin() {

System.out.println("Login with " + username);

@Factory

public static Object[] factoryMethod() {

return new Object[] {

new LoginTest("user1"),

new LoginTest("user2")

};

Interview Tip:
Mention factories are powerful when each test instance needs a unique setup (e.g., multi-user
testing).

Q100. How do you integrate TestNG with Maven and Jenkins?

Detailed Explanation:

 Use maven-surefire-plugin in pom.xml to run TestNG suites.

 Jenkins executes tests via Maven build step (mvn test -PRegression).

Example pom snippet:

<plugin>
<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-surefire-plugin</artifactId>

<version>3.1.2</version>

<configuration>

<suiteXmlFiles>

<suiteXmlFile>testng.xml</suiteXmlFile>

</suiteXmlFiles>

</configuration>

</plugin>
Interview Tip:
Highlight CI integration and how TestNG results were published automatically in Jenkins reports.

Section 7 – Selenium WebDriver Advanced Concepts (Q101–Q120)

Q101. What are the different types of locators in Selenium? Which one is most preferred and why?

Detailed Explanation:
Locators are used to identify web elements in Selenium. Choosing the correct locator directly
impacts test reliability and maintainability.

Types of Locators:

1. id – Fastest and most reliable (if unique).


Example: driver.findElement(By.id("username"))

2. name – Used when id is not available.

3. className – Targets elements by class (less reliable if multiple elements share same class).

4. tagName – Finds all elements of a specific HTML tag.

5. linkText / partialLinkText – Used for <a> elements.

6. cssSelector – Very powerful, supports combinations.


Example: driver.findElement(By.cssSelector("input#username"))

7. xpath – Supports both HTML structure and conditions.


Example: driver.findElement(By.xpath("//input[@type='text']"))

Best Practice:

 Prefer ID > CSS Selector > XPath (in that order).

 Use relative XPath (//) instead of absolute (/html/body/...).


Interview Tip:
Explain you use CSS for speed and cleaner syntax, and fall back to XPath for dynamic or complex
hierarchies.

Q102. What is the difference between absolute and relative XPath?

Detailed Explanation:

 Absolute XPath: Starts from the root (/html/...).


→ Fails easily if UI layout changes.
Example: /html/body/div[2]/div[1]/input

 Relative XPath: Starts from any node (//) and is more flexible.
Example: //input[@name='username']

Why Relative XPath is preferred:


UI layouts often change; relative XPath focuses on element attributes rather than structure.

Interview Tip:
Show how you use functions like contains(), starts-with(), or dynamic attributes in XPath.

Q103. How do you handle dynamic elements whose attributes change frequently?

Detailed Explanation:
Dynamic elements (like IDs that change every load) cause flaky tests.

Techniques to handle:

1. Use contains() or starts-with() in XPath:

2. driver.findElement(By.xpath("//input[contains(@id,'user')]"));

3. Use parent-child or sibling relationships:

4. //label[text()='Username']/following-sibling::input

5. Use custom attributes (like data-test).

6. Introduce explicit waits to ensure element stability before interaction.

Interview Tip:
Explain how you created dynamic XPaths using partial matches and stabilized flaky locators using
WebDriverWait.

Q104. What is the difference between findElement() and findElements()?

Detailed Explanation:
Method Description Returns Behavior when not found

Finds the first matching Single Throws


findElement()
element WebElement NoSuchElementException

findElements() Finds all matching elements List<WebElement> Returns empty list

Example:

List<WebElement> links = driver.findElements(By.tagName("a"));

System.out.println("Links found: " + links.size());

Interview Tip:
Mention you use findElements() in validations (e.g., verifying no duplicates or counting rows).

Q105. What are implicit, explicit, and fluent waits?

Detailed Explanation:
Selenium waits handle synchronization issues between the test and the browser.

1. Implicit Wait:
Applies globally for all element searches.

2. driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

3. Explicit Wait (WebDriverWait):


Waits for specific condition before continuing.

4. WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

5. wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("login")));

6. Fluent Wait:
Polls periodically until condition is met or timeout expires.

7. Wait<WebDriver> wait = new FluentWait<>(driver)

8. .withTimeout(Duration.ofSeconds(30))

9. .pollingEvery(Duration.ofSeconds(5))

10. .ignoring(NoSuchElementException.class);

Best Practice:
Use Explicit Waits for specific element actions and Implicit Waits for global baseline.

Interview Tip:
Explain how replacing Thread.sleep() with smart waits reduced flakiness in your project.

Q106. What are different types of exceptions you have faced in Selenium?

Common Selenium Exceptions:


Exception Cause

NoSuchElementException Element not found

StaleElementReferenceException DOM refreshed after locating element

ElementClickInterceptedException Element not clickable due to overlay

TimeoutException Wait condition not met

NoAlertPresentException Alert not available

WebDriverException Browser crashed or session not reachable

Handling Example:

try {

driver.findElement(By.id("login")).click();

} catch (NoSuchElementException e) {

System.out.println("Element not found!");

Interview Tip:
Mention you’ve handled flaky exceptions by adding retries and wait conditions.

Q107. How do you handle frames in Selenium?

Detailed Explanation:
Web pages may have <iframe> elements, and Selenium can’t access inner content until you switch to
it.

Methods:

// By index

driver.switchTo().frame(0);

// By name or ID

driver.switchTo().frame("frameName");

// By WebElement

WebElement frame = driver.findElement(By.xpath("//iframe[@id='loginFrame']"));

driver.switchTo().frame(frame);
// Return to default

driver.switchTo().defaultContent();

Interview Tip:
Explain that frame handling is critical for pages with embedded widgets like payment gateways.

Q108. How do you handle multiple browser windows or tabs in Selenium?

Detailed Explanation:
Use getWindowHandles() and switchTo().window().

Example:

String parent = driver.getWindowHandle();

Set<String> windows = driver.getWindowHandles();

for (String win : windows) {

driver.switchTo().window(win);

if (driver.getTitle().contains("Checkout")) {

break;

Interview Tip:
Describe a real case — for example, verifying payment or help pages opened in new tabs.

Q109. How to handle alerts and pop-ups in Selenium?

Types of Alerts:

1. Simple Alert → alert.accept()

2. Confirmation Alert → alert.dismiss()

3. Prompt Alert → alert.sendKeys("text")

Example:

Alert alert = driver.switchTo().alert();

System.out.println(alert.getText());

alert.accept();

Interview Tip:
Add that you use ExpectedConditions.alertIsPresent() to avoid timing issues.
Q110. How do you perform mouse and keyboard actions?

Detailed Explanation:
Use the Actions class for advanced user interactions.

Example:

Actions act = new Actions(driver);

act.moveToElement(driver.findElement(By.id("menu"))).click().build().perform();

act.keyDown(Keys.CONTROL).click(elem).keyUp(Keys.CONTROL).perform();

Common Use-Cases:

 Mouse hover menus

 Drag and drop

 Right click (context click)

 Keyboard shortcuts

Interview Tip:
Mention you implemented hover-based submenus or drag-drop in test scenarios.

Q111. How do you handle file uploads in Selenium?


Detailed Explanation:
If the <input type="file"> is visible:

driver.findElement(By.id("fileUpload")).sendKeys("/path/to/file.txt");

If hidden (using system dialog), use:

 Robot class

 AutoIt (Windows only)

 JavaScript Executor

Interview Tip:
Mention for CI/CD compatibility you prefer direct sendKeys() method over Robot.

Q112. What is JavaScriptExecutor and why is it used?

Detailed Explanation:
When Selenium APIs cannot perform an action (e.g., hidden elements), JavaScriptExecutor executes
JS commands directly in the browser.

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript("arguments[0].click();", element);

Use-Cases:

 Scrolling

 Clicking hidden elements

 Extracting values not visible in DOM

Interview Tip:
Give an example where element.click() failed and JavaScriptExecutor solved it.

Q113. What is Page Object Model (POM)?

Detailed Explanation:
POM is a design pattern where each page is represented as a class with locators and methods.

Example:

public class LoginPage {

WebDriver driver;

@FindBy(id="userEmail") WebElement username;

@FindBy(id="userPassword") WebElement password;

public LoginPage(WebDriver driver) {

this.driver = driver;

PageFactory.initElements(driver, this);

public void login(String user, String pass) {

username.sendKeys(user);

password.sendKeys(pass);

Benefits:

 Reusability

 Maintainability

 Reduces duplication
Interview Tip:
Mention how you built your framework with POM + PageFactory pattern.

Q114. What is the difference between Page Object Model and Page Factory?

Detailed Explanation:

 POM: The concept/pattern — page as a class.

 Page Factory: A Selenium class that initializes elements annotated with @FindBy.

Example:

@FindBy(id="loginBtn")

WebElement loginBtn;

Without PageFactory, you’d use:

WebElement loginBtn = driver.findElement(By.id("loginBtn"));

Interview Tip:
Mention PageFactory improves readability but you ensure lazy loading and null safety.

Q115. How do you take screenshots in Selenium?

Example:

TakesScreenshot ts = (TakesScreenshot) driver;

File src = ts.getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(src, new File("./screenshots/error.png"));

Automation Tip:
Integrate this in your TestNG Listeners to capture screenshots on failures.

Q116. How do you handle SSL certificate errors in Selenium?

Detailed Explanation:
Use browser options to bypass SSL warnings.

Example (Chrome):

ChromeOptions options = new ChromeOptions();

options.setAcceptInsecureCerts(true);

driver = new ChromeDriver(options);

Interview Tip:
Mention you configured browser profiles in CI to auto-accept SSL for testing environments.
Q117. How do you handle dropdowns in Selenium?

Detailed Explanation:
Use Select class for <select> elements.

Example:

Select select = new Select(driver.findElement(By.id("country")));

select.selectByVisibleText("India");

select.selectByIndex(2);

select.selectByValue("IN");

Interview Tip:
For non-select dropdowns, mention using Actions or direct click()s.

Q118. How do you handle Shadow DOM elements?

Detailed Explanation:
Standard Selenium can’t access Shadow DOM directly. Use JavaScript to pierce it.

Example:

WebElement shadowHost = driver.findElement(By.cssSelector("shadow-host"));

WebElement shadowRoot = (WebElement) ((JavascriptExecutor) driver)

.executeScript("return arguments[0].shadowRoot", shadowHost);

WebElement inner = shadowRoot.findElement(By.cssSelector("#innerElement"));

Interview Tip:
Highlight that Shadow DOM handling is essential for modern web apps built with frameworks like
Polymer or Lit.

Q119. How do you upload files when file input is not accessible (hidden)?

Answer:
When <input type="file"> is hidden, direct sendKeys() won’t work.
Use:

 JavaScriptExecutor to make it visible.

 Robot class or AutoIt to handle OS-level dialogs.

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("document.querySelector('#upload').style.display='block';");

driver.findElement(By.id("upload")).sendKeys("/path/to/file.txt");
Q120. How do you maximize test reusability and reduce duplication in Selenium?

Detailed Explanation:

1. Use Page Object Model for reusing page functions.

2. Create BaseTest class for setup/teardown.

3. Maintain utilities (e.g., WaitHelper, ScreenshotHelper).

4. Externalize data in Excel/Properties/JSON.

5. Use custom wrapper methods (e.g., clickElement(By)).

Example:

public void clickElement(By locator) {

new WebDriverWait(driver, Duration.ofSeconds(10))

.until(ExpectedConditions.elementToBeClickable(locator))

.click();

Interview Tip:
Explain how you created a utility library to avoid repeating WebDriver code.

Section 8 – Automation Framework Design (Q121–Q140)

Q121. What is an automation framework and why is it needed?

Detailed Explanation:
An automation framework is a structured approach to writing and maintaining test scripts efficiently.
It provides a reusable foundation that defines:

 How tests are written

 How test data is managed

 How results are reported

 How environment setup/teardown is handled

Key Benefits:

 Improves test reusability

 Reduces maintenance effort

 Enhances consistency

 Supports CI/CD integration


 Enables scalability (multiple modules & teams)

Example Framework Components:

src/

main/java/

base/

utilities/

pageObjects/

test/java/

testCases/

testData/

config/

reports/

drivers/
Interview Tip:
Describe your framework layers (BaseTest, PageObjects, Utilities, Data, Reports) and emphasize
maintainability and modularity.

Q122. What are the key components of a Selenium automation framework?

Detailed Explanation:

1. Test Scripts – Test scenarios written using framework methods.

2. Page Objects – Classes that encapsulate locators and actions.

3. Test Data Management – External files (Excel, CSV, JSON, DB).

4. Utility Classes – Common reusable functions (Waits, Screenshots).

5. Configuration Management – Property files for environment and credentials.

6. Test Runner – TestNG or JUnit classes to execute suites.

7. Reports and Logs – Extent Reports, Log4j, or Allure.

8. Build Tool Integration – Maven/Gradle for dependencies.

9. CI/CD Integration – Jenkins for scheduled or triggered builds.

Interview Tip:
When asked about framework structure, be specific — e.g., “We used Page Object + TestNG + Extent
Reports integrated with Jenkins.”
Q123. What is a Hybrid Framework in Selenium?

Detailed Explanation:
A Hybrid Framework combines features of multiple frameworks like Data-Driven, Keyword-Driven,
and Modular frameworks.

Example:

 Data-driven → Fetch data from Excel/JSON.

 Keyword-driven → Use keywords like “click”, “enterText” to trigger actions.

 Modular → Divide tests into reusable functional modules.

Benefits:

 Maximum flexibility

 High reusability

 Easy maintenance

Example Flow:

Excel → Keywords → Execution Engine → Selenium Actions

Interview Tip:
Explain your hybrid setup — e.g., “Our framework used data-driven logic from Excel and keywords to
define test steps dynamically.”

Q124. What is the difference between Data-Driven and Keyword-Driven frameworks?

Feature Data-Driven Keyword-Driven

Focus Varying input data Actions/keywords to be executed

Data Source External files (Excel, CSV) External file defining action keywords

Example Login with multiple users “Click”, “EnterText”, “Submit”

Used When Input varies Steps vary dynamically

Interview Tip:
Explain both can be merged for flexibility — your hybrid framework used data from Excel and
keywords for reusable steps.

Q125. How do you design a Data-Driven Framework in Selenium?

Detailed Explanation:

 Externalize test data from the code.

 Use libraries like Apache POI, OpenCSV, or JSON.simple.


 Parameterize test cases using TestNG @DataProvider.

Example (Excel DataReader):

public Object[][] getData() throws IOException {

FileInputStream fis = new FileInputStream("data.xlsx");

XSSFWorkbook workbook = new XSSFWorkbook(fis);

XSSFSheet sheet = workbook.getSheet("Login");

int rows = sheet.getLastRowNum();

int cols = sheet.getRow(0).getLastCellNum();

Object[][] data = new Object[rows][cols];

for(int i=0; i<rows; i++){

for(int j=0; j<cols; j++){

data[i][j] = sheet.getRow(i+1).getCell(j).toString();

return data;

Interview Tip:
State you decoupled data from logic, allowing multiple user credential combinations to run
dynamically.

Q126. How is test data managed in your framework?

Detailed Explanation:
Common Data Management Approaches:

1. Excel-based — using Apache POI.

2. CSV-based — lightweight and easy for Jenkins pipelines.

3. JSON or YAML — structured data for APIs or config-driven UIs.

4. Database — fetch test data directly from QA DB.

5. Property Files — for environment URLs, credentials.

Best Practice:

 Keep data in a separate /testData/ folder.

 Use a DataUtil class to fetch and cache data.


 Support environment-based datasets (QA/Stage/Prod).

Interview Tip:
Mention you used JSON for API validations and Excel for UI tests to maintain uniformity.

Q127. What is a Keyword-Driven Framework and how is it implemented?

Detailed Explanation:
In a Keyword-Driven Framework, test steps are written as keywords in an external file (Excel or
XML). Each keyword maps to a method in the automation library.

Example Excel:

TestCase Action Locator Value

Login click id=loginBtn

Login enterText id=username user1

Login enterText id=password pass123

Execution Engine:

switch(keyword) {

case "click": driver.findElement(By.id(locator)).click(); break;

case "enterText": driver.findElement(By.id(locator)).sendKeys(value); break;

Interview Tip:
Say your framework supported non-technical users to write Excel-based keywords for tests.

Q128. What is a Modular Framework and how do you design it?

Detailed Explanation:
A Modular Framework divides the application under test into independent modules. Each module
has its own test scripts and reusable functions.

Example:

modules/

login/

cart/

checkout/

Benefits:

 Code reuse across modules.


 Easier debugging and maintenance.

 Clear separation of functionality.

Interview Tip:
Explain that when one module changes (e.g., login), only that script is updated, not the entire suite.

Q129. What is the purpose of a BaseTest class?

Detailed Explanation:
BaseTest is the foundation of most frameworks. It handles:

 WebDriver initialization

 Browser setup and teardown

 Configuration loading

 Reporting integration

Example:

public class BaseTest {

protected WebDriver driver;

@BeforeMethod

public void setUp() {

driver = new ChromeDriver();

driver.manage().window().maximize();

@AfterMethod

public void tearDown() {

driver.quit();

Interview Tip:
Mention all test classes extend BaseTest, ensuring consistent setup and cleanup.

Q130. How do you manage configuration and environment variables?

Detailed Explanation:
Use config.properties and System properties.

Example:
browser=chrome

url=https://qa.portal.com

timeout=10

Code to Read Config:

Properties prop = new Properties();

FileInputStream fis = new FileInputStream("config.properties");

prop.load(fis);

String browser = prop.getProperty("browser");

Interview Tip:
Explain that CI pipelines (Jenkins) override configs dynamically with -Denv=qa.

Q131. What is the purpose of a Utility or Helper class?

Detailed Explanation:
Utilities are reusable functions common across tests:

 WaitHelper

 ScreenshotUtil

 ExcelUtil

 BrowserUtil

 LogUtil

Example:

public class WaitHelper {

public static void waitForVisible(WebDriver driver, By locator) {

new WebDriverWait(driver, Duration.ofSeconds(10))

.until(ExpectedConditions.visibilityOfElementLocated(locator));

Interview Tip:
Show you organized your utilities in a separate utils package for modularity.

Q132. How do you design reporting in your framework?

Detailed Explanation:
Integrate Extent Reports or Allure Reports for professional results.
Example (Extent Reports):

ExtentReports extent = new ExtentReports();

ExtentTest test = extent.createTest("LoginTest");

test.log(Status.PASS, "Login successful");

extent.flush();

Output:
An HTML report with step-level logs, colors, and screenshots.

Interview Tip:
Mention that your reports automatically attach screenshots on failure via TestNG Listeners.

Q133. What is the role of Log4j or logging in frameworks?

Detailed Explanation:
Logging helps in debugging and audit trails.

Example (log4j2.xml):

<Logger name="LoginTest" level="info" additivity="false">

<AppenderRef ref="Console"/>

<AppenderRef ref="File"/>

</Logger>

Usage:

private static Logger log = LogManager.getLogger(LoginTest.class);

log.info("Login started");

Interview Tip:
State that logging improves traceability, especially in CI failures.

Q134. What are the benefits of using Maven in your framework?

Detailed Explanation:

 Dependency management via pom.xml.

 Build automation (mvn clean test).

 Environment profiles for QA/UAT/Prod.

 CI/CD compatibility.

Example (pom.xml dependency):

<dependency>
<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.22.0</version>

</dependency>

Interview Tip:
Mention using Maven profiles (-PRegression) to run specific test suites.

Q135. What is continuous integration (CI) and how does it fit into test automation?

Detailed Explanation:
CI is the practice of integrating code changes frequently and validating them automatically.

In Automation:

 Jenkins triggers test runs automatically on code commits.

 Reports and logs are archived for each build.

Interview Tip:
Say, “Our CI pipeline runs smoke tests on every commit and regression nightly.”

Q136. How do you integrate your framework with Jenkins?

Steps:

1. Install Maven & TestNG plugins in Jenkins.

2. Create a new job → select Git repository and branch.

3. Add build step:

4. mvn clean test -PRegression

5. Publish HTML report post-build.

Interview Tip:
Mention you parameterized builds for dynamic environment selection (-Denv=qa).

Q137. What are Extent Reports and how do you integrate them?

Detailed Explanation:
Extent Reports provides visually rich test execution reports.

Integration:

 Initialize report in @BeforeSuite.

 Log steps using ExtentTest.

 Flush results in @AfterSuite.


Example:

test.log(Status.INFO, "User logged in");

test.addScreenCaptureFromPath("error.png");

Interview Tip:
Highlight that screenshots are captured automatically through Listeners.

Q138. How do you manage cross-browser testing in your framework?

Detailed Explanation:

 Configure browser in config.properties.

 Initialize WebDriver based on the browser value.

Example:

if(browser.equalsIgnoreCase("chrome"))

driver = new ChromeDriver();

else if(browser.equalsIgnoreCase("firefox"))

driver = new FirefoxDriver();

Interview Tip:
Mention Selenium Grid or cloud platforms (BrowserStack, LambdaTest) for scalable cross-browser
runs.

Q139. What is Selenium Grid and how do you use it?

Detailed Explanation:
Selenium Grid enables distributed parallel execution across multiple machines or browsers.

Architecture:

 Hub: Central controller.

 Node: Machine where test runs.

Command Example:

java -jar selenium-server-standalone.jar hub

java -jar selenium-server-standalone.jar node --hub http://localhost:4444/grid/register

Interview Tip:
State that you used Grid to run regression tests across Chrome, Firefox, and Edge in parallel.

Q140. How do you maintain framework scalability and version control?

Detailed Explanation:
1. Use Git for version control.

2. Maintain branching strategy (main/dev/feature).

3. Modularize framework structure for easy expansion.

4. Maintain CI/CD triggers per branch.

Interview Tip:
Say your team followed GitFlow branching and used pull requests for peer review before merging to
main.

Section 9 – API Testing and Integration (Q141–Q160)

Q141. What is API testing and why is it important?

Detailed Explanation:
API testing validates the backend logic, data exchange, and response handling of an application
without using the UI. It ensures that:

 Endpoints return correct responses.

 Data is correctly sent, processed, and stored.

 Business logic works independently of the front end.

Benefits:

 Faster than UI tests.

 Detects defects early in backend logic.

 Ideal for CI/CD pipelines.

 Reduces UI automation load.

Example:
Testing a “Login API” that accepts JSON body:

"username": "user1",

"password": "pass123"

You check whether the API returns 200 OK and a valid token.

Interview Tip:
Emphasize API testing helps identify defects before UI layers are built, saving time and effort.

Q142. What are the types of API protocols?


Detailed Explanation:

1. REST (Representational State Transfer) — Lightweight, uses HTTP.

2. SOAP (Simple Object Access Protocol) — XML-based, strict schema.

3. GraphQL — Single endpoint, flexible query structure.

4. gRPC — Fast binary protocol used in microservices.

Interview Tip:
Mention that REST APIs are most common and you’ve tested them using Postman and Rest Assured.

Q143. What are the main HTTP methods used in REST APIs?

Method Purpose Example

GET Retrieve data /users

POST Create data /users

PUT Update/replace data /users/1

PATCH Partially update data /users/1

DELETE Delete data /users/1

Interview Tip:
Explain how you validated CRUD operations using different HTTP methods in automation scripts.

Q144. What are the main parts of an HTTP request?

Detailed Explanation:

1. Endpoint (URL) – API address

2. Method – GET, POST, PUT, DELETE

3. Headers – Metadata like Content-Type, Authorization

4. Body – Data (JSON/XML) sent with POST/PUT requests

Example:

POST /login HTTP/1.1

Host: api.example.com

Content-Type: application/json

"username": "user1",

"password": "pass123"
}

Interview Tip:
Mention how you dynamically construct headers and bodies using Java Maps in Rest Assured.

Q145. What are the main parts of an HTTP response?

Response Structure:

1. Status Code – 200, 400, 404, 500

2. Headers – Server info, content type

3. Body – JSON/XML payload

Example Response:

"id": 101,

"name": "Deepika",

"role": "QA"

Interview Tip:
Be ready to list status code categories:

 1xx – Informational

 2xx – Success

 3xx – Redirection

 4xx – Client error

 5xx – Server error

Q146. What tools do you use for API testing?

Common Tools:

 Postman – Manual API testing & collections.

 Rest Assured – Java library for API automation.

 SoapUI – For SOAP and complex services.

 Karate DSL – Combines API and UI testing.

Interview Tip:
Mention you start with Postman for exploration, then automate stable endpoints using Rest Assured.
Q147. What is Rest Assured, and why is it used for API automation?

Detailed Explanation:
Rest Assured is a Java-based library that simplifies testing RESTful APIs. It uses a readable syntax
similar to Gherkin.

Advantages:

 Built on top of HTTP client.

 Integrates with TestNG/JUnit.

 Supports JSON/XML.

 Handles authentication and schema validation.

Example:

given()

.baseUri("https://api.example.com")

.contentType("application/json")

.body("{\"username\":\"user1\", \"password\":\"pass123\"}")

.when()

.post("/login")

.then()

.statusCode(200)

.body("token", notNullValue());

Interview Tip:
Highlight that Rest Assured fits perfectly into hybrid Selenium-TestNG frameworks.

Q148. How do you validate JSON response fields in Rest Assured?

Detailed Explanation:
Use .body() with JSON path expressions.

Example:

Response response = given().get("/users/1");

response.then().assertThat().body("name", equalTo("Deepika"));

Advanced:

String city = response.jsonPath().getString("address.city");

Assert.assertEquals(city, "Hyderabad");

Interview Tip:
Explain JSONPath is powerful for deeply nested response validation.
Q149. How do you validate status codes and headers in Rest Assured?

Example:

given()

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

.then()

.statusCode(200)

.header("Content-Type", "application/json; charset=utf-8");

Interview Tip:
Mention validating both body and headers ensures full response correctness.

Q150. How do you pass query parameters and path parameters in Rest Assured?

Example with Query Param:

given().queryParam("page", 2).when().get("/users");

Example with Path Param:

given().pathParam("userId", 101).when().get("/users/{userId}");

Interview Tip:
State that query params are used for filters/pagination, and path params for specific records.

Q151. How do you handle authentication in API testing?

Types of Authentication:

 Basic Auth: username + password

 Bearer Token (OAuth2): JWT token

 API Key: key passed in header

 OAuth 2.0: Multi-step token flow

Example:

given().auth().basic("admin", "password").when().get("/dashboard");

Bearer Token Example:

given().header("Authorization", "Bearer " + token)

.when().get("/profile");

Interview Tip:
Describe how you fetch access tokens dynamically in pre-test setup.
Q152. What is the difference between authentication and authorization?

Term Purpose

Authentication Verifies user identity (login)

Authorization Grants access to resources post-login

Interview Example:

 Authentication → /login

 Authorization → /admin/dashboard
Interview Tip:
Give an example: “I validated that unauthorized users get 403 response.”

Q153. How do you handle POST requests with JSON body in Rest Assured?

Example:

JSONObject body = new JSONObject();

body.put("name", "Deepika");

body.put("job", "QA Engineer");

given()

.contentType("application/json")

.body(body.toString())

.when()

.post("/users")

.then()

.statusCode(201);

Interview Tip:
Mention you use dynamic JSON creation via Map or POJO for reusability.

Q154. How do you perform schema validation in API testing?

Detailed Explanation:
Schema validation ensures that response structure matches the expected JSON schema.

Example:

given()
.get("/users/1")

.then()

.assertThat()

.body(matchesJsonSchemaInClasspath("userSchema.json"));

Interview Tip:
State that schema validation helps detect missing or extra fields early.

Q155. How do you integrate API tests with Selenium UI tests?

Detailed Explanation:
API tests can support UI tests by:

 Pre-creating test data via API before UI tests.

 Validating UI data using backend APIs.

 Cleaning up after UI tests.

Example:

String orderId = given().body(orderJson)

.post("/createOrder")

.jsonPath().getString("orderId");

// Use orderId in UI validation

driver.findElement(By.id("orderSearch")).sendKeys(orderId);

Interview Tip:
Mention this hybrid integration significantly reduces UI test time.

Q156. How do you handle dynamic values in API testing (like tokens or IDs)?

Detailed Explanation:
Capture dynamic data from API responses and reuse them in subsequent requests.

Example:

String token = given().body(credentials)

.post("/login")

.jsonPath().getString("token");

given().header("Authorization", "Bearer " + token)


.get("/profile")

.then().statusCode(200);

Interview Tip:
Show that chaining requests helps maintain test flow realism.

Q157. How do you manage test data in API testing frameworks?

Detailed Explanation:

 Use JSON or CSV files for request bodies.

 Parameterize using TestNG DataProvider.

 Create utility methods to build dynamic JSON payloads.

Example:

Map<String, Object> data = new HashMap<>();

data.put("name", "Deepika");

data.put("age", 29);

given().body(data).post("/users");

Interview Tip:
Mention you maintain a payloadBuilder class to centralize request templates.

Q158. What is the difference between PUT and PATCH methods?

Method Purpose Behavior

PUT Replaces entire resource Overwrites

PATCH Updates partial fields Modifies only specified fields

Example:

// PUT

given().body("{\"name\":\"Deepika\",\"role\":\"QA\"}").put("/users/1");

// PATCH

given().body("{\"role\":\"Lead QA\"}").patch("/users/1");

Interview Tip:
State that PATCH is faster and used for minor updates.
Q159. How do you validate performance in API testing?

Detailed Explanation:

 Use Rest Assured .time() method or performance tools like JMeter.

 Set maximum acceptable response time (SLA).

Example:

long time = given().get("/users").time();

Assert.assertTrue(time < 2000);

Interview Tip:
Highlight that you validate response times in CI to ensure no performance degradation.

Q160. How do you integrate API automation with CI/CD pipelines?

Detailed Explanation:

1. Use Maven + TestNG for execution.

2. Jenkins job runs API test suite (mvn clean test -PAPI).

3. Reports (Extent or Allure) get published post-run.

4. Pipeline triggers automatically on code commit or nightly build.

Interview Tip:
Explain how your pipeline runs both UI and API suites separately and merges reports for unified view.

Section 10 Database Testing and Validation (Q161–Q180)

Q161. What is database testing and why is it important?

Detailed Explanation:
Database testing ensures that data stored, updated, or retrieved by the application is correct and
consistent. It involves verifying:

 Data integrity

 Data consistency

 CRUD operations (Create, Read, Update, Delete)

 Stored procedures and triggers

Why it’s important:

 Ensures the UI displays accurate data.

 Detects backend issues early.


 Prevents data corruption or mismatches between modules.

Example:
After submitting a “New Order” on UI, you check in DB:

SELECT * FROM Orders WHERE OrderID = 1234;

Interview Tip:
Mention that in your projects you validated DB entries after UI actions (like verifying user creation or
order submission).

Q162. What are the different types of database testing?

Detailed Explanation:

1. Structural Testing:

o Checks schema, tables, relationships, and indexes.

2. Functional Testing:

o Validates business logic, stored procedures, and triggers.

3. Data Integrity Testing:

o Ensures foreign keys and constraints maintain data consistency.

4. Regression Testing:

o Verifies that DB changes don’t break existing functionality.

Interview Tip:
Say you performed data validation and referential integrity checks post UI actions.

Q163. What is JDBC and why is it used in automation testing?

Detailed Explanation:
JDBC (Java Database Connectivity) is an API that enables Java applications to connect to databases,
execute queries, and fetch results.

Why used in automation:


To connect the test scripts to the DB and verify whether backend data matches UI/API results.

Architecture:

Application → JDBC API → JDBC Driver → Database

Interview Tip:
Mention that you use JDBC in Selenium/Rest Assured frameworks for data validation.

Q164. How do you connect to a database using JDBC in Java?

Example Code:
Connection conn = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/shopdb", "user", "password");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id=1");

while(rs.next()){

System.out.println(rs.getString("username"));

rs.close();

stmt.close();

conn.close();

Interview Tip:
Explain that connection details (URL, username, password) are stored in config files, not hardcoded.

Q165. How do you validate data between UI and database?

Scenario Example:

1. Enter data on UI → “Create Customer”.

2. Fetch the same customer from DB → verify all fields match.

Example Code:

String uiValue = driver.findElement(By.id("custName")).getText();

Connection con = DriverManager.getConnection(DB_URL, USER, PASS);

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT name FROM customers WHERE id=101");

rs.next();

String dbValue = rs.getString("name");

Assert.assertEquals(uiValue, dbValue);

Interview Tip:
Emphasize end-to-end validation — from UI → API → DB.
Q166. What are some common SQL commands used in testing?

Operation SQL Command Example

Retrieve SELECT SELECT * FROM users;

Insert INSERT INTO INSERT INTO users VALUES (1,'Deepika');

Update UPDATE UPDATE users SET city='Hyderabad' WHERE id=1;

Delete DELETE DELETE FROM users WHERE id=1;

Filter WHERE SELECT * FROM users WHERE city='Delhi';

Sort ORDER BY SELECT * FROM users ORDER BY id DESC;

Interview Tip:
Mention you frequently used SELECT queries for data verification and JOIN for relational data checks.

Q167. How do you handle database connections efficiently in automation?

Best Practices:

 Use a singleton utility class for DB connection reuse.

 Close connections in finally block or using try-with-resources.

 Avoid keeping long-lived open connections.

Example:

public class DBUtil {

private static Connection con;

public static Connection getConnection() throws SQLException {

if(con == null || con.isClosed()) {

con = DriverManager.getConnection(DB_URL, USER, PASS);

return con;

Interview Tip:
Highlight connection pooling or utility reuse for efficiency.

Q168. How do you verify if data is deleted successfully in DB?

Approach:
1. Perform delete operation on UI.

2. Execute SQL:

3. SELECT COUNT(*) FROM users WHERE id=101;

4. Expect count = 0.

Example:

ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM users WHERE id=101");

rs.next();

Assert.assertEquals(rs.getInt(1), 0);

Interview Tip:
Say you use count-based validation to confirm deletions instead of catching exceptions.

Q169. How do you handle SQL exceptions in Java?

Detailed Explanation:
Handle using try-catch or throw it to higher layers.

Example:

try {

Connection con = DriverManager.getConnection(DB_URL, USER, PASS);

} catch(SQLException e) {

e.printStackTrace();

Best Practice:
Use logging (log.error(e.getMessage())) and fail test gracefully.

Interview Tip:
Show you have error handling for connection failures in CI/CD pipelines.

Q170. How do you parameterize SQL queries in Java?

Detailed Explanation:
Use PreparedStatement to prevent SQL injection and improve performance.

Example:

PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id=?");

ps.setInt(1, 101);

ResultSet rs = ps.executeQuery();
Interview Tip:
Explain that using PreparedStatement avoids hardcoding and SQL injection risks.

Q171. What is data integrity testing in DB?

Detailed Explanation:
Data integrity testing ensures the accuracy and consistency of data over its lifecycle.

Types of Integrity:

 Entity Integrity → Primary key not null/unique

 Referential Integrity → Foreign keys valid

 Domain Integrity → Data type, format, range

Example:
Check that OrderID in Orders exists in Customers table.

Interview Tip:
Highlight your experience validating foreign key consistency after transactional operations.

Q172. What is database migration testing?

Detailed Explanation:
When DB schema changes (new columns, constraints), migration testing ensures no data loss or
corruption occurs.

Example:

 Before migration: Backup data from users.

 After migration: Validate record counts, schema match.

Interview Tip:
Mention DB migration testing during version upgrades or cloud migrations (e.g., on AWS RDS).

Q173. How do you automate SQL validations as part of Selenium framework?

Detailed Explanation:

 Create a DB Utility class with reusable methods (connect, query, close).

 Call DB verification inside test flow.

Example:

public String getOrderStatus(int orderId) {

ResultSet rs = executeQuery("SELECT status FROM orders WHERE id=" + orderId);

rs.next();
return rs.getString("status");

In Test:

Assert.assertEquals(getOrderStatus(1234), "Shipped");

Interview Tip:
Explain you integrated DB validations to ensure backend reflects UI actions correctly.

Q174. What is a JOIN in SQL? What are its types?

Type Description Example

INNER Returns records with matching keys in SELECT * FROM Orders o INNER JOIN Customers c
JOIN both tables ON o.CustID = c.ID

Returns all from left + matched from


LEFT JOIN
right

RIGHT
All from right + matched from left
JOIN

All records where match exists in


FULL JOIN
either table

Interview Tip:
Give a real example: verifying customer names joined with order details.

Q175. How do you verify numeric and string data types in DB testing?

Example:

DESC customers;

→ Ensures id is INT, name is VARCHAR.

Automation Check:

ResultSetMetaData meta = rs.getMetaData();

String type = meta.getColumnTypeName(1); // e.g. "INT"

Interview Tip:
Say you validated column data types during schema regression tests.

Q176. How do you perform backend data valSectionidation for APIs?

Example Flow:

1. API → POST /createUser


2. Capture userId from response.

3. Verify in DB:

4. SELECT * FROM users WHERE id = userId;

Code Example:

String userId = given().post("/createUser").jsonPath().getString("id");

ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE id="+userId);

Assert.assertTrue(rs.next());

Interview Tip:
Mention integrating DB verification after successful API calls.

Q177. What are stored procedures and how do you test them?
Detailed Explanation:
Stored Procedures are SQL code blocks stored in DB that perform tasks like data insert/update.

Execution:

CALL updateUserStatus(101, 'Active');

Automation Example:

CallableStatement cs = con.prepareCall("{call updateUserStatus(?,?)}");

cs.setInt(1, 101);

cs.setString(2, "Active");

cs.execute();

Interview Tip:
Say you tested stored procedures to ensure they perform correct updates and rollbacks.

Q178. How do you test triggers in a database?

Detailed Explanation:
A trigger automatically executes after insert/update/delete events.

Example:
Trigger on “Orders” updates “Inventory” when a new order is placed.

Test Flow:

1. Insert into Orders.

2. Check Inventory table for quantity decrement.

Interview Tip:
Explain you validated trigger logic by verifying impact on dependent tables.
Q179. How do you ensure your automation framework supports multiple databases (e.g., MySQL,
Oracle, SQL Server)?

Detailed Explanation:

 Use configuration-driven DB connection setup.

 Maintain DB type in config:

 dbType=oracle

 dbURL=jdbc:oracle:thin:@localhost:1521:orcl

 Switch driver dynamically:

 if(dbType.equals("mysql"))

 Class.forName("com.mysql.cj.jdbc.Driver");
Interview Tip:
Highlight your framework supports multi-DB testing by externalizing connection parameters.

Q180. What are some best practices for database testing in automation?

Best Practices:

1. Separate test and production DBs.

2. Clean up data after test runs.

3. Use transactions and rollbacks.

4. Keep DB credentials secure.

5. Validate both structure and data.

6. Automate high-risk, high-impact DB checks.

Interview Tip:
Conclude by saying you ensure data accuracy, referential integrity, and transaction safety in all DB
validations.

Section 11 – Behavior-Driven Development (BDD) Using Cucumber (Q181–Q200)

Q181. What is BDD (Behavior-Driven Development)?

Detailed Explanation:
BDD is a software development approach that bridges the communication gap between technical
and non-technical stakeholders by describing system behavior in plain English using structured
formats.

It focuses on what the system should do, not how it does it.

Key Features:

 Uses natural language (Gherkin).

 Promotes collaboration between QA, developers, and business analysts.

 Drives automation through shared understanding of requirements.

Example:
A login feature written in Gherkin:

Feature: Login Functionality

Scenario: Successful login with valid credentials

Given User is on Login Page

When User enters valid username and password

Then User should be navigated to the Home Page

Interview Tip:
Say: “BDD helps ensure everyone speaks the same language — testers, developers, and business
teams.”

Q182. What is Cucumber in BDD?

Detailed Explanation:
Cucumber is an open-source tool that supports BDD. It reads Gherkin feature files and maps them
to step definitions (Java, Python, JS, etc.) for automation.

Cucumber executes:

 Feature Files → describe behavior

 Step Definitions → implement test logic

 Hooks → setup/teardown logic


Interview Tip:
Explain that you use Cucumber to automate scenarios written by business analysts, making them
executable.

Q183. What is Gherkin syntax?

Detailed Explanation:
Gherkin is a domain-specific language used to write Cucumber scenarios in plain English.

Gherkin Keywords:
 Feature

 Scenario

 Given → setup/precondition

 When → action

 Then → expected result

 And, But → additional steps

Example:

Given user navigates to the login page

When user enters correct credentials

Then home page is displayed

Interview Tip:
Mention that Gherkin makes tests readable and traceable to user stories.

Q184. What are the components of a Cucumber framework?

Main Components:

1. Feature Files – Written in Gherkin, describing behavior.

2. Step Definition Files – Contain Java methods implementing Gherkin steps.

3. Hooks – Contain setup and teardown (@Before, @After).

4. Runner Class – Executes feature files using JUnit/TestNG.

5. Page Objects (Optional) – Used for UI automation structure.

Interview Tip:
Say your project used Page Object Model + Cucumber for modular and maintainable design.

Q185. How do you create and structure a Cucumber project in Eclipse?

Steps:

1. Create a Maven Project.

2. Add dependencies:

3. <dependency>

4. <groupId>io.cucumber</groupId>

5. <artifactId>cucumber-java</artifactId>

6. <version>7.15.0</version>

7. </dependency>
8. <dependency>

9. <groupId>io.cucumber</groupId>

10. <artifactId>cucumber-junit</artifactId>

11. <version>7.15.0</version>

12. </dependency>

13. Create package structure:

14. src/test/java

15. |-- features/

16. |-- stepDefinitions/

17. |-- runners/

18. |-- hooks/

19. Write feature files and implement step definitions.

Interview Tip:
Mention that Maven simplifies dependency management, and pom.xml controls the entire setup.

Q186. What is a Feature File?

Detailed Explanation:
A feature file describes a user feature or functionality in business-readable format.

Example:

Feature: Search functionality

Scenario: Search product by name

Given user is on the homepage

When user searches for "Laptop"

Then results for "Laptop" should be displayed

Interview Tip:
Explain that each feature corresponds to one business module or epic.

Q187. What is a Step Definition File?

Detailed Explanation:
A step definition file links the Gherkin steps to executable Java code.

Example:
@Given("user is on the homepage")

public void user_is_on_homepage() {

driver.get("https://rahulshettyacademy.com");

Interview Tip:
Say: “Each Gherkin step must have one matching annotated method in a Step Definition class.”

Q188. What is a Runner Class in Cucumber?

Detailed Explanation:
The runner file integrates Cucumber with JUnit or TestNG and triggers execution of feature files.

Example (JUnit Runner):

@RunWith(Cucumber.class)

@CucumberOptions(

features = "src/test/java/features",

glue = "stepDefinitions",

plugin = {"pretty", "html:target/cucumber-reports.html"},

tags = "@Smoke"

public class TestRunner {}

Interview Tip:
Explain that you can run Cucumber tests selectively using tags in the runner file.

Q189. What are Hooks in Cucumber?

Detailed Explanation:
Hooks are like setup and teardown methods executed before or after each scenario.

Example:

@Before

public void setup() {

driver = new ChromeDriver();

@After
public void teardown() {

driver.quit();

Interview Tip:
Say you use Hooks for driver initialization, login, or database cleanup.

Q190. What are Tags in Cucumber?

Detailed Explanation:
Tags categorize and filter test cases for execution.

Example:

@Smoke @Login

Scenario: Verify valid login

In Runner:

@CucumberOptions(tags = "@Smoke")

Interview Tip:
Mention that tags help run subsets like @Smoke, @Regression, or @Sanity.

Q191. What is Scenario Outline in Cucumber?

Detailed Explanation:
Scenario Outline allows data-driven testing using Examples tables.

Example:

Scenario Outline: Login with multiple users

Given user is on login page

When user logs in with <username> and <password>

Then user should see homepage

Examples:

| username | password |

| user1 | pass123 |

| user2 | pass456 |

Interview Tip:
Say Scenario Outline eliminates redundant test steps for multiple data sets.
Q192. What are Backgrounds in Cucumber?

Detailed Explanation:
Background is used to define steps common to all scenarios within a feature.

Example:

Background:

Given user is logged in

Scenario: Search product

When user searches for "Phone"

Then results are displayed

Interview Tip:
Use Background only when setup steps are identical across all scenarios.

Q193. What are Data Tables in Cucumber?

Detailed Explanation:
Data tables are used to pass structured data to step definitions.

Example:

When user registers with following details

| Name | Email | Password |

| John | [email protected] | abc123 |

Step Definition:

@When("user registers with following details")

public void register(DataTable dataTable) {

List<Map<String,String>> data = dataTable.asMaps();

System.out.println(data.get(0).get("Name"));

Interview Tip:
Mention data tables simplify bulk input handling in tests like user registration.

Q194. How do you perform parameterization in Cucumber?

Detailed Explanation:
Use regular expressions in step definitions to accept dynamic values.

Example:
When user logs in with username "Deepika" and password "QA123"

Step Definition:

@When("^user logs in with username (.+) and password (.+)$")

public void login(String username, String password) {

loginPage.login(username, password);

Interview Tip:
Explain regex parameterization reduces code duplication.

Q195. How do you handle multiple step definition files in Cucumber?

Detailed Explanation:
Use glue option in the runner class to specify multiple packages:

@CucumberOptions(glue = {"stepDefinitions", "hooks"})

Interview Tip:
Say you separate logic into module-based step definitions for scalability.

Q196. How do you integrate Cucumber with Selenium?

Detailed Explanation:

1. Use Selenium for browser interactions in step definitions.

2. Launch driver in Hooks.

3. Maintain POM structure for reusability.

Example:

@When("user searches for {string}")

public void user_searches(String product) {

driver.findElement(By.id("search")).sendKeys(product);

driver.findElement(By.id("searchBtn")).click();

Interview Tip:
Explain Cucumber only handles test flow; Selenium performs actual automation.

Q197. How do you generate reports in Cucumber?

Detailed Explanation:
Cucumber provides multiple built-in reporting plugins:
 pretty – console logs

 html – HTML reports

 json – for Jenkins or Allure

Example:

plugin = {"pretty", "html:target/cucumber-reports.html", "json:target/cucumber.json"}

Interview Tip:
Mention you used Extent or Allure reports for enhanced visuals and Jenkins integration.

Q198. How do you run Cucumber tests from command line or Jenkins?

Command Line:

mvn test -Dcucumber.options="--tags @Smoke"

Jenkins Integration:

 Create Maven job.

 Add build step → mvn clean test.

 Post-build → publish Cucumber HTML reports.

Interview Tip:
Highlight that Jenkins runs Cucumber tests as part of CI pipeline with scheduled triggers.

Q199. What is the difference between Cucumber and TestNG frameworks?

Feature Cucumber TestNG

Approach BDD (Behavior Driven) TDD (Test Driven)

Syntax Gherkin (plain English) Java annotations

Audience Business + QA + Dev QA + Dev

Focus Behavior Functionality

Reusability Scenario-based Method-based

Interview Tip:
Say you combine both: “We use Cucumber for BDD and TestNG for parallel execution & reporting.”

Q200. What are the advantages and limitations of Cucumber BDD?

Advantages:

 Improves collaboration across teams.


 Plain English readability.

 Reusable step definitions.

 Integrates easily with Selenium & API tools.

Limitations:

 Can become complex for large test suites.

 Slower than plain TestNG in some cases.

 Requires disciplined structure for maintainability.

Interview Tip:
Mention that with good tagging and modular design, Cucumber remains highly scalable.

Section 12 – Continuous Integration (CI/CD) & Jenkins (Q201–Q220)

Q201. What is Continuous Integration (CI) and why is it important in automation testing?

Detailed Explanation:
Continuous Integration (CI) is the practice of frequently integrating code into a shared repository
and automatically verifying it through builds and tests.

Why it’s important:

 Ensures new code doesn’t break existing functionality.

 Enables faster feedback for developers.

 Keeps the codebase stable at all times.

 Automatically runs regression suites after each commit.

Example:
When a developer pushes new code → Jenkins triggers an automated test run → QA gets results
immediately.

Interview Tip:
Say you configured Jenkins jobs that run Selenium + API tests after every Git commit.

Q202. What is Jenkins and how does it support CI/CD?

Detailed Explanation:
Jenkins is an open-source CI/CD tool written in Java that automates building, testing, and
deployment of applications.

Key Features:

 Supports Maven, Git, and Docker integration.

 Allows job scheduling and pipeline creation.


 Provides plugins for reporting and notifications.

Interview Tip:
Say you use Jenkins to trigger nightly regression builds and publish automation reports.

Q203. How do you install Jenkins?

Steps:

1. Download Jenkins .war from https://jenkins.io.

2. Run using terminal:

3. java -jar jenkins.war

4. Access Jenkins at http://localhost:8080.

5. Unlock with initial admin password.

6. Install suggested plugins.

7. Create an admin user and start using Jenkins.

Interview Tip:
Mention you also configured Jenkins on a Linux server using yum install jenkins in production setup.

Q204. How do you configure Jenkins to run Selenium or Maven tests?

Detailed Explanation:

1. Install Jenkins Maven and Git plugins.

2. Create a new Freestyle project.

3. Add:

o Git repository URL

o Build command:

o mvn clean test

4. Post-build action: Publish HTML/Extent reports.

Interview Tip:
Explain that you configured Jenkins to pull code from GitHub and run the Selenium regression suite
automatically.

Q205. What are Jenkins Pipelines?

Detailed Explanation:
Jenkins Pipeline is a suite of plugins that allows defining CI/CD workflows as code using a Jenkinsfile.

Advantages:
 Version-controlled.

 Supports stages (Build, Test, Deploy).

 Scripted or Declarative syntax.

Example Jenkinsfile:

pipeline {

agent any

stages {

stage('Build') {

steps {

sh 'mvn clean compile'

stage('Test') {

steps {

sh 'mvn test'

stage('Report') {

steps {

publishHTML(target: [

reportDir: 'target',

reportFiles: 'cucumber-reports.html',

reportName: 'Automation Report'

])

Interview Tip:
Mention that your team uses Declarative Pipelines for better readability and modularity.
Q206. How do you trigger Jenkins jobs automatically?

Detailed Explanation:

1. SCM Polling: Jenkins checks Git for new commits periodically.

2. Webhook Trigger: GitHub triggers Jenkins instantly after each push.

3. Scheduled Builds: Use CRON syntax (H 2 * * *) for nightly runs.

Interview Tip:
Say: “We used GitHub Webhooks to trigger Jenkins builds instantly on every merge to the main
branch.”

Q207. How do you pass parameters in Jenkins jobs?

Detailed Explanation:
Use Parameterized Builds to pass environment-specific values (like browser, URL, or environment).

Steps:

1. Enable “This project is parameterized”.

2. Add String parameters like BROWSER or ENV.

3. Reference them in build steps:

4. mvn test -DBrowser=$BROWSER -DEnv=$ENV

Interview Tip:
Say you use parameterized Jenkins builds to test across QA, UAT, and Prod environments.

Q208. How do you integrate Jenkins with GitHub?

Steps:

1. Install Git Plugin in Jenkins.

2. Configure repository URL in job.

3. Use credentials (SSH key or token).

4. Add GitHub webhook:

o Go to GitHub repo → Settings → Webhooks

o Add Jenkins URL /github-webhook/

Interview Tip:
Mention you used webhooks for continuous testing integration with GitHub commits.

Q209. How do you generate reports from Jenkins builds?

Detailed Explanation:
 For TestNG → Use emailable-report.html.

 For Cucumber → Use plugin:

 plugin: ["json:target/cucumber.json", "html:target/cucumber-reports.html"]

 Publish reports in Jenkins:

o Post-build → “Publish HTML Reports” → set directory as target.

Interview Tip:
Say your Jenkins jobs automatically archive reports and send email notifications to stakeholders.

Q210. What is the difference between Freestyle and Pipeline jobs in Jenkins?

Feature Freestyle Pipeline

Setup GUI-based Code-based (Jenkinsfile)

Reusability Low High

Version Control No Yes

Flexibility Limited Very high

Best For Simple jobs End-to-end CI/CD

Interview Tip:
Say: “We migrated from Freestyle to Jenkinsfile-based Pipelines for maintainability and Git
versioning.”

Q211. How do you schedule builds in Jenkins?

Detailed Explanation:

 Go to Job → Build Triggers → Build periodically

 Add CRON syntax:

 H2***

→ Runs daily at 2 AM.

Interview Tip:
Mention you scheduled nightly regression jobs and configured auto-report emails on completion.

Q212. How do you integrate Jenkins with Maven?

Detailed Explanation:

1. Install Maven plugin in Jenkins.


2. Configure Maven under Global Tool Configuration.

3. Add build step:

4. mvn clean test -PRegression

5. Use pom.xml to handle dependencies.

Interview Tip:
Say you use Maven + Jenkins to ensure consistent dependency management across builds.

Q213. How do you integrate Selenium tests with Jenkins?

Detailed Explanation:

1. Jenkins pulls Selenium project from Git.

2. Executes tests using Maven:

3. mvn clean test

4. Publishes HTML or Extent reports.

5. Can trigger tests on remote nodes using Selenium Grid.

Interview Tip:
Mention Jenkins executes your Selenium + Cucumber suite daily with Extent HTML reports.

Q214. How do you handle environment variables in Jenkins?

Detailed Explanation:

 Define environment variables in Jenkins under Build Environment.

 Access in script using:

 echo $BROWSER

or in Java:

System.getenv("BROWSER");

Interview Tip:
Say you externalized environment variables for flexible, environment-agnostic test runs.

Q215. How do you send email notifications from Jenkins?

Detailed Explanation:

1. Install Email Extension Plugin.

2. Configure SMTP under Manage Jenkins → Configure System.

3. Add Editable Email Notification post-build action.


4. Use triggers like:

o On success/failure.

o Include report attachments.

Interview Tip:
Say you configured Jenkins to send pass/fail summary + HTML report links to team members.

Q216. How do you execute parallel testing using Jenkins?

Detailed Explanation:
Use Jenkins pipeline stages or TestNG parallel execution.

Example:

parallel (

chrome: { sh 'mvn test -Dbrowser=chrome' },

firefox: { sh 'mvn test -Dbrowser=firefox' }

Interview Tip:
Mention parallel execution helped reduce regression time by 50%.

Q217. What are Jenkins nodes, agents, and masters?

Detailed Explanation:

 Master → Controls the pipeline and job scheduling.

 Agent (Node) → Executes the jobs.

 Slave → Another term for an agent machine.

Interview Tip:
Say: “We configured multiple Jenkins agents to run tests across OS and browser combinations.”

Q218. How do you secure Jenkins?

Best Practices:

 Enable user authentication.

 Use Role-Based Access Control plugin.

 Integrate with LDAP if needed.

 Avoid storing passwords in plain text; use Jenkins credentials store.

 Keep Jenkins and plugins updated.


Interview Tip:
Mention that you used Jenkins credentials store for Git tokens and AWS secrets.

Q219. What is a Jenkinsfile and how is it used?

Detailed Explanation:
Jenkinsfile defines your CI/CD pipeline as code and lives inside your Git repository.

Example:

pipeline {

agent any

stages {

stage('Build') { steps { sh 'mvn clean compile' } }

stage('Test') { steps { sh 'mvn test' } }

stage('Deploy') { steps { sh './deploy.sh' } }

Interview Tip:
Say Jenkinsfile enables version control and better maintainability of pipelines.

Q220. What are the best practices for using Jenkins in automation projects?

Best Practices:

1. Use Jenkinsfile for pipeline-as-code.

2. Trigger builds via Git hooks.

3. Maintain separate jobs for UI, API, and DB tests.

4. Archive reports and logs.

5. Use environment-specific parameters.

6. Integrate Slack/Email notifications.

7. Clean up workspace post-build.

Interview Tip:
Say: “We follow CI/CD best practices — code → test → report → deploy, all through Jenkins pipeline
automation.”

Section 13 – Version Control Using Git & GitHub (Q221–Q240)


Q221. What is Git and why is it used in automation testing?

Detailed Explanation:
Git is a distributed version control system used to track changes in source code. It allows multiple
team members to work on the same project simultaneously without conflicts.

Why testers use Git:

 Store and version-control test scripts, data files, and reports.

 Revert to older versions if new commits break tests.

 Collaborate efficiently using branches and pull requests.

 Integrate with Jenkins for CI/CD.

Interview Tip:
Say: “We use Git to maintain automation code, manage parallel feature development, and trigger
Jenkins builds.”

Q222. What is GitHub and how is it related to Git?

Detailed Explanation:
GitHub is a cloud-based hosting platform for Git repositories.
It provides:

 Central repository for collaboration.

 Issue tracking and project management.

 Pull requests and code reviews.

 CI/CD integration with Jenkins, GitHub Actions, etc.

Interview Tip:
Say Git is the tool, GitHub is the service that hosts and manages repositories.

Q223. How do you initialize a Git repository in your project?

Commands:

cd /path/to/project

git init

This creates a hidden .git folder to track changes locally.

Then add and commit files:

git add .

git commit -m "Initial commit"


Interview Tip:
Explain that you initialize Git in every new automation framework to maintain version history.
Q224. How do you clone an existing repository from GitHub?

Command:

git clone https://github.com/deepikadev533/AutomationFramework.git

Explanation:
Creates a local copy of a remote repository on your machine.

Interview Tip:
Mention that you often clone automation repositories to contribute or debug issues locally.

Q225. What is the purpose of git add and git commit commands?

Command Purpose Example

git add Stages changes for commit git add file.java

git commit Saves staged changes with a message git commit -m "Added login tests"

Interview Tip:
Explain the staging concept — files must be added (add) before being committed (commit).

Q226. What is a branch in Git and why do we use it?

Detailed Explanation:
A branch represents an independent line of development.
It allows multiple testers or developers to work on features without affecting the main codebase.

Example Commands:

git branch feature-login

git checkout feature-login

Interview Tip:
Say you use feature branches for new test modules, then merge them into main after review.

Q227. How do you merge a branch in Git?

Steps:

1. Switch to target branch:

2. git checkout main

3. Merge feature branch:

4. git merge feature-login


Interview Tip:
Say: “After QA automation scripts are reviewed, we merge feature branches into the main branch to
trigger Jenkins.”

Q228. What are merge conflicts and how do you resolve them?

Detailed Explanation:
Merge conflicts occur when two branches modify the same line in a file.

Steps to resolve:

1. Open conflicting file — look for:

2. <<<<<<< HEAD

3. your code

4. =======

5. other branch code

6. >>>>>>> feature-branch

7. Manually fix and save.

8. Run:

9. git add <file>

10. git commit -m "Resolved conflict"

Interview Tip:
Say you often resolve merge conflicts when parallel automation updates happen on shared test files.

Q229. How do you push changes to a remote repository?

Command:

git push origin main

 origin = remote repo name.

 main = branch name.

Interview Tip:
Mention you use SSH or personal access tokens (PAT) for authentication since password-based
pushes are deprecated.

Q230. How do you pull the latest code from the repository?

Command:

git pull origin main


Explanation:
Fetches the latest changes from the remote repo and merges them into your local branch.

Interview Tip:
Say you always pull before starting new work to avoid conflicts.

Q231. How do you check the current status of your Git repo?

Command:

git status

Output shows:

 Modified files.

 Untracked files.

 Files staged for commit.

Interview Tip:
Say: “I use git status regularly to ensure I only commit intended changes.”

Q232. What is the purpose of .gitignore file?

Detailed Explanation:
The .gitignore file tells Git which files or folders to exclude from tracking.

Example:

target/

logs/

*.class

config.properties

Interview Tip:
Say you exclude build folders, reports, and credentials files for security and cleanliness.

Q233. What is the difference between git fetch and git pull?

Command Function Behavior

git fetch Downloads latest commits Doesn’t merge

git pull Fetches + merges Updates local branch immediately

Interview Tip:
Say you use git fetch to review remote changes before merging them.
Q234. How do you revert a commit in Git?

Command:

git revert <commit-id>

Explanation:
Creates a new commit that undoes the changes of the given commit without rewriting history.

Interview Tip:
Say you use revert when a faulty test script breaks Jenkins build.

Q235. How do you remove untracked files in Git?

Command:

git clean -f

Removes files not tracked by Git (e.g., temporary or generated files).

Interview Tip:
Mention it’s useful to clean workspace before merging or pushing updates.

Q236. How do you check commit history in Git?

Command:

git log

Options:

git log --oneline --graph --decorate

Displays a compact, visual branch history.

Interview Tip:
Say you use commit history to trace who modified a test module or configuration.

Q237. What is a Pull Request (PR)?

Detailed Explanation:
A Pull Request is a request to merge your branch changes into another branch (usually main) on
GitHub.

Flow:

1. Push branch to GitHub.

2. Create PR → Assign reviewers.

3. Review, approve, merge.


Interview Tip:
Say PRs ensure code quality, peer review, and avoid direct merges.

Q238. What are Git tags, and when do you use them?

Detailed Explanation:
Tags mark specific points in Git history (e.g., release versions).

Example:

git tag -a v1.0 -m "Release 1.0"

git push origin v1.0

Interview Tip:
Mention you tag stable releases like “Regression_Pass_v3.2” before major deployments.

Q239. How do you integrate Git with Jenkins for automation?

Steps:

1. Install Git Plugin in Jenkins.

2. Configure repository URL in job.

3. Add credentials (token or SSH key).

4. Enable triggers (e.g., “Build when a change is pushed to GitHub”).

5. Jenkins pulls latest code and executes mvn test.

Interview Tip:
Say Jenkins-Git integration ensures continuous testing on every commit.

Q240. What are the best practices for using Git in test automation projects?

Best Practices:

1. Always pull before pushing.

2. Commit small, logical changes with clear messages.

3. Use branching strategy:

o main → stable

o develop → active work

o feature/* → new test modules

4. Don’t commit credentials or binary files.

5. Use PRs for code review.


6. Tag stable builds.

7. Sync with CI tools like Jenkins.

Interview Tip:
Say: “Following Git branching and PR reviews improved our automation code stability and
collaboration.”

Section 14 – Test Strategy, Planning & Reporting (Q241–Q260)

Q241. What is a Test Strategy, and why is it important?

Detailed Explanation:
A Test Strategy is a high-level document that defines the approach, objectives, resources, and scope
of testing across all phases of a project.

It answers “how testing will be done” and ensures alignment between QA, Dev, and Business teams.

Key Elements:

 Testing scope (in-scope / out-of-scope)

 Testing levels (Unit, Integration, System, UAT)

 Testing types (Functional, Regression, Security, Performance)

 Tools & environments

 Defect management process

 Exit criteria

Example:
For a healthcare app:

 In-scope: Claim processing, member login

 Out-of-scope: Backend DB maintenance

Interview Tip:
Say: “I created a project-wide Test Strategy that aligned automation and manual efforts for end-to-
end validation.”

Q242. What is a Test Plan? How is it different from a Test Strategy?

Feature Test Plan Test Strategy

Level Project/Module Organization/Program

Ownership QA Lead/Manager QA Manager/Architect


Feature Test Plan Test Strategy

Scope Specific release or sprint Entire product lifecycle

Content Objectives, resources, schedule Policies, approach, tools

Dynamic? Can change per sprint Stable over time

Example:
A Test Plan for Release 1.2 defines test objectives, timelines, and roles for that release;
A Test Strategy defines how testing will be done across all releases.

Interview Tip:
Say: “I developed detailed Test Plans derived from our organization-level Test Strategy.”

Q243. What are the key components of a Test Plan?

Components:

1. Test Objectives

2. Scope (In / Out)

3. Test Approach

4. Test Environment

5. Test Deliverables

6. Entry and Exit Criteria

7. Risk and Mitigation Plan

8. Schedule and Milestones

9. Resource Planning

10. Tools and Automation Framework

Interview Tip:
Mention you created Test Plans in Excel, Word, or ALM/Azure DevOps for all major releases.

Q244. How do you estimate testing effort?

Detailed Explanation:
Effort estimation predicts how long testing activities will take, considering scope and complexity.

Common Methods:

 Work Breakdown Structure (WBS): Break testing into small tasks.

 Test Case Point Method: Based on number and complexity of test cases.

 Experience-based: Historical data from similar projects.


Example:

Module A: 50 test cases × 30 min = 25 hours

Module B: 80 test cases × 20 min = 26.6 hours

Total = 51.6 hours

Interview Tip:
Say: “I use test case complexity and past velocity to estimate QA efforts per sprint.”

Q245. What is Risk-Based Testing?

Detailed Explanation:
Risk-Based Testing prioritizes test cases based on the likelihood and impact of failures.

Steps:

1. Identify critical business areas.

2. Assign risk scores (High/Medium/Low).

3. Prioritize test execution accordingly.

Example:

 Login, Payment modules → High risk

 Profile updates → Medium

 UI styling → Low

Interview Tip:
Say: “In one release, we prioritized testing claim validation logic first, as it impacted billing directly.”

Q246. What is Entry and Exit Criteria in testing?

Detailed Explanation:

Criteria Description Example

Conditions that must be met before Test environment ready, build deployed, test data
Entry
testing starts prepared

100% critical test cases executed, no high-severity


Exit Conditions to declare testing complete
defects open

Interview Tip:
Say you defined clear Entry/Exit criteria in every Test Plan to maintain release discipline.

Q247. What is a Test Scenario vs. Test Case?


Term Description Example

Test
High-level user flow “Verify user can log in”
Scenario

Detailed step-by-step Enter username, enter password, click login, verify


Test Case
validation homepage

Interview Tip:
Say: “Scenarios help visualize user journeys; cases ensure complete validation.”

Q248. How do you prioritize test cases?

Based on:

 Business impact

 Frequency of use

 Defect-prone areas

 Regulatory or compliance risk

 Time constraints

Example:

1. High – Login, Checkout, Payments

2. Medium – User Profile

3. Low – About Us Page

Interview Tip:
Say you used Priority + Severity matrix in ALM/Azure DevOps to prioritize effectively.

Q249. What is Test Coverage and how do you measure it?

Definition:
Test Coverage = The degree to which requirements are tested.

Formula:

Test Coverage (%) = (Number of Requirements Tested / Total Requirements) × 100

Example:

 80 of 100 requirements tested → 80% coverage.

Interview Tip:
Say: “We achieved 95% functional and 80% automation coverage in regression.”

Q250. What are Test Metrics?


Definition:
Test Metrics are quantitative measures to evaluate testing progress and quality.

Common Metrics:

 Test Case Execution %

 Defect Density

 Pass/Fail Rate

 Automation Coverage

 Test Effort Variance

 Defect Leakage

Interview Tip:
Mention you tracked metrics in Excel dashboards or tools like Power BI or Azure DevOps.

Q251. What is Defect Density and Defect Leakage?

Metric Formula Example

Defect Density Defects / Module Size (e.g., LOC or Function Points) 25 defects / 500 LOC = 0.05

Defect Leakage (Defects found in UAT / Total defects) × 100 (5/50)×100 = 10%

Interview Tip:
Say: “We reduced defect leakage from 18% to 8% by improving regression coverage.”

Q252. How do you track and report QA progress?

Detailed Explanation:

 Use Test Management Tools (JIRA, ALM, ADO).

 Maintain Daily Execution Dashboards.

 Include:

o Total cases executed

o Passed/Failed/Pending count

o Defects logged/resolved

o Risk summary

Example:

Metric Count

Total Test Cases 200


Metric Count

Executed 180

Passed 160

Failed 20

Interview Tip:
Say: “I shared daily QA status reports with stakeholders including blockers and risk updates.”

Q253. What is Traceability Matrix and why is it important?

Detailed Explanation:
A Traceability Matrix (RTM) maps requirements to corresponding test cases to ensure 100%
requirement coverage.

Example:

Req ID Description Test Case ID Status

R1 Login TC001, TC002 Pass

R2 Add to Cart TC010 Fail

Interview Tip:
Say you maintained RTM in Excel or ALM to avoid missed test coverage.

Q254. How do you ensure quality in Agile testing?

Detailed Explanation:

 Participate in sprint planning.

 Collaborate closely with Dev & Product Owners.

 Test early and continuously.

 Automate regression.

 Conduct exploratory testing in each sprint.

Interview Tip:
Say: “I ensured every user story had test cases and acceptance criteria before sprint commitment.”

Q255. What is Exploratory Testing?

Detailed Explanation:
Exploratory testing is unscripted testing where testers explore the application using intuition and
experience to uncover unexpected issues.
When to use:

 When documentation is limited.

 During early or unstable builds.

 For new feature shakedowns.

Interview Tip:
Say: “I complement structured test cases with exploratory sessions to catch edge defects.”

Q256. How do you ensure test data management?

Best Practices:

 Use anonymized or masked production data.

 Store test data in versioned repositories.

 Create data setup scripts for automation.

 Refresh data regularly for consistency.

Interview Tip:
Mention your team built automated test data generators for consistent regression testing.

Q257. How do you handle test environment issues?

Approach:

1. Identify environment blockers early (DB, APIs, access).

2. Maintain environment checklist.

3. Escalate blockers immediately via defect or risk logs.

4. Use mock APIs if backend unavailable.

Interview Tip:
Say you worked with DevOps teams to ensure environment stability for test runs.

Q258. How do you review and improve testing processes?

Steps:

 Conduct retrospectives after every sprint.

 Review defect trends.

 Identify repetitive issues and fix root causes.

 Automate redundant regression flows.


Example:
Found login regression failures in 3 sprints → implemented API mock + data reset → issue resolved.

Interview Tip:
Say: “We implemented continuous QA improvement via metrics-driven retrospectives.”

Q259. What is the difference between Verification and Validation?

Term Focus Example

Verification Ensures product is built correctly Reviews, inspections, static testing

Validation Ensures product meets requirements Functional testing, UAT

Interview Tip:
Say: “Verification = Are we building right? Validation = Are we building the right thing?”

Q260. What are QA deliverables in a project lifecycle?

Deliverables:

 Test Strategy Document

 Test Plan

 Test Cases / Scenarios

 Test Data

 Traceability Matrix

 Test Execution Report

 Defect Reports

 QA Sign-Off Document

Interview Tip:
Mention that QA deliverables ensure accountability and compliance in every release.

Section 15 – Advanced Automation Framework Design (Q261–Q280)

Q261. What is an Automation Framework?

Detailed Explanation:
An automation framework is a structured, reusable set of guidelines, components, and tools that
help automate test scripts efficiently and consistently.

It defines how tests are created, executed, and maintained — ensuring scalability, modularity, and
reporting.
Key Components:

 Test scripts

 Object repositories

 Utilities (e.g., file readers, data providers)

 Reporting mechanism

 Configuration files

 Logging

Interview Tip:
Say: “A well-designed framework reduces maintenance effort and enables faster onboarding of new
testers.”

Q262. What are the different types of automation frameworks?

Framework Type Description Example

Linear / Record &


Sequential scripts, minimal reuse UFT basic recording
Playback

Modular Framework Code divided into reusable modules LoginModule, SearchModule

Different inputs for same


Data-Driven Test data externalized (Excel, JSON, DB)
test

Keyword-Driven Uses keywords for actions login, click, verify

Combines data-driven + keyword +


Hybrid Most common
modular

BDD Framework Behavior-driven using Cucumber Scenarios written in Gherkin

Interview Tip:
Mention your experience with Hybrid POM + Cucumber framework for Selenium and API testing.

Q263. What are the advantages of a good automation framework?

Benefits:

1. Reusability of code

2. Easy maintenance

3. Scalability

4. Better reporting

5. Consistent test execution


6. Cross-browser and environment support

Interview Tip:
Say: “Our hybrid framework allowed us to reduce regression execution time by 60%.”

Q264. What is Page Object Model (POM)?

Detailed Explanation:
POM is a design pattern that creates a class for each web page, encapsulating web elements and
actions related to that page.

Benefits:

 Reduces code duplication

 Improves readability

 Easier maintenance

Example:

public class LoginPage {

WebDriver driver;

By username = By.id("userEmail");

By password = By.id("userPassword");

By loginBtn = By.id("login");

public LoginPage(WebDriver driver) {

this.driver = driver;

public void login(String user, String pass) {

driver.findElement(username).sendKeys(user);

driver.findElement(password).sendKeys(pass);

driver.findElement(loginBtn).click();

Interview Tip:
Say you use POM with BaseTest and utility classes for cleaner code architecture.
Q265. What is the folder structure of a typical Selenium Hybrid Framework?

Example Structure:

src/test/java/

├── pageObjects/

├── testCases/

├── utilities/

├── testData/

├── reports/

├── resources/

├── config.properties

├── log4j2.xml

pom.xml

Interview Tip:
Explain how each folder has a defined responsibility (POM, test data, utilities, configuration, reports).

Q266. What is the BaseTest class and why is it used?

Detailed Explanation:
The BaseTest class is a parent class that initializes the WebDriver, configurations, and reporting.
All test classes extend this class.

Example:

public class BaseTest {

public WebDriver driver;

@BeforeMethod

public void setup() {

driver = new ChromeDriver();

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

driver.get("https://app.under.test/");

@AfterMethod

public void tearDown() {


driver.quit();

Interview Tip:
Say BaseTest reduces code redundancy and centralizes setup logic.

Q267. How do you manage configurations in your framework?

Detailed Explanation:
Use a config.properties file for environment-specific data:

browser=chrome

url=https://app.test.com

username=admin

password=pass123

Utility Code:

Properties prop = new Properties();

FileInputStream fis = new FileInputStream("config.properties");

prop.load(fis);

String browser = prop.getProperty("browser");

Interview Tip:
Say: “We externalized configurations to make the framework flexible across environments.”

Q268. How do you handle multiple browsers in Selenium framework?

Example (Factory Design Pattern):

public WebDriver initializeDriver(String browser) {

if (browser.equalsIgnoreCase("chrome"))

driver = new ChromeDriver();

else if (browser.equalsIgnoreCase("firefox"))

driver = new FirefoxDriver();

else if (browser.equalsIgnoreCase("edge"))

driver = new EdgeDriver();

return driver;

}
Interview Tip:
Mention cross-browser compatibility testing using Selenium Grid or parallel execution in TestNG.

Q269. How do you manage test data in your framework?

Options:

 Excel: Apache POI

 JSON: JSONSimple or Jackson library

 Database: JDBC

 DataProvider: For parameterization in TestNG

Example (DataProvider):

@DataProvider(name="loginData")

public Object[][] getData() {

return new Object[][] {{"user1", "pass1"}, {"user2", "pass2"}};

Interview Tip:
Say: “We built a data-driven framework using Excel sheets and TestNG DataProviders.”

Q270. How do you manage logs in your framework?

Detailed Explanation:
Use Log4j2 or SLF4J to track execution flow.

log4j2.xml Example:

<Logger name="TestLogger" level="info" additivity="false">

<AppenderRef ref="FileAppender"/>

</Logger>

Usage:

private static Logger log = LogManager.getLogger(TestClass.class);

log.info("Launching browser...");

Interview Tip:
Say you use Log4j2 for detailed execution tracking and debugging.

Q271. How do you generate reports in your framework?

Common Tools:
 Extent Reports (most popular)

 Allure Reports

 Cucumber HTML (for BDD frameworks)

Example (Extent Report):

ExtentReports extent = new ExtentReports();

ExtentTest test = extent.createTest("Login Test");

test.pass("Login successful");

extent.flush();

Interview Tip:
Mention: “We used Extent Reports integrated with Jenkins for visually rich reporting.”

Q272. How do you handle test dependencies and build automation?

Detailed Explanation:
Use Maven for:

 Dependency management

 Build execution (mvn clean test)

 Plugin integration

pom.xml Example:

<dependency>

<groupId>org.seleniumhq.selenium</groupId>

<artifactId>selenium-java</artifactId>

<version>4.23.0</version>

</dependency>

Interview Tip:
Say Maven ensures consistent builds and smooth integration with Jenkins.

Q273. How do you implement parallel execution in your framework?

Detailed Explanation:
Use TestNG with parallel attribute in testng.xml:

<suite name="ParallelTests" parallel="tests" thread-count="2">

<test name="ChromeTest">

<parameter name="browser" value="chrome"/>


<classes><class name="tests.LoginTest"/></classes>

</test>

<test name="FirefoxTest">

<parameter name="browser" value="firefox"/>

<classes><class name="tests.LoginTest"/></classes>

</test>

</suite>

Interview Tip:
Say: “Parallel execution helped us cut regression time from 3 hours to 1.5.”

Q274. What are reusable utility classes in your framework?

Common Utility Classes:

 WebDriverUtils: waits, alerts, scrolling

 ExcelUtils: data reading

 PropertyUtils: config management

 ScreenshotUtils: capture on failure

Example:

public static void captureScreenshot(WebDriver driver, String name) {

File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(src, new File("./reports/" + name + ".png"));

Interview Tip:
Mention reusable utilities promote code reusability and cleaner test scripts.

Q275. What is a TestNG listener, and how is it used in frameworks?

Detailed Explanation:
Listeners monitor test execution and perform actions based on test events (start, success, failure).

Example:

public class Listeners extends TestListenerAdapter {

public void onTestFailure(ITestResult result) {

System.out.println("Test failed: " + result.getName());

}
}

In testng.xml:

<listeners>

<listener class-name="utilities.Listeners"/>

</listeners>

Interview Tip:
Say you used listeners for screenshot capture and report logging on test failure.

Q276. How do you manage test execution order in TestNG?

Options:

1. priority attribute

2. dependsOnMethods

3. dependsOnGroups

Example:

@Test(priority=1)

public void login() {}

@Test(priority=2, dependsOnMethods="login")

public void addProduct() {}

Interview Tip:
Mention dependency management ensures logical test flow and prevents false failures.

Q277. How do you integrate APIs or Database tests into your Selenium framework?

Approach:

 Create separate modules for API and DB testing.

 Use Rest Assured for API validation.

 Use JDBC for DB checks.

 Integrate results into unified Extent Report.

Example:

String response = given().get("/user").asString();

Assert.assertTrue(response.contains("Deepika"));
Interview Tip:
Say you unified UI + API + DB automation under one Maven project for full-stack validation.

Q278. What is CI/CD integration in framework context?

Detailed Explanation:
Your framework integrates with Jenkins (or GitHub Actions) to enable:

 Automatic builds

 Parallel execution

 Centralized reporting

Example:

mvn clean test -PRegression

Interview Tip:
Say: “Each commit triggers Jenkins, which executes the automation suite and sends HTML reports via
email.”

Q279. How do you make your framework scalable and maintainable?

Best Practices:

1. Follow design patterns (POM, Singleton, Factory).

2. Modularize code (per feature).

3. Externalize data/configs.

4. Use constants and enums.

5. Maintain clean naming conventions.

6. Implement version control via Git.

Interview Tip:
Say: “We built a scalable hybrid framework reused across multiple microservices applications.”

Q280. What are common challenges faced in framework design and how did you overcome them?

Challenges & Solutions:

Challenge Solution

High maintenance due to frequent UI changes Used dynamic XPaths and Page Factory

Long execution time Parallel execution + API pre-validation

Environment instability Mock servers + retry logic


Challenge Solution

Unreadable reports Extent HTML reports with screenshots

Multiple browser handling Cross-browser factory class

Interview Tip:
Say: “We continuously improved framework efficiency by analyzing failure trends and optimizing
architecture.”

Section 16 – Test Reporting, Monitoring & QA Metrics (Q281–Q300)

Q281. What is the purpose of test reporting in automation?

Detailed Explanation:
Test reporting provides visibility into the test execution results, defects, and overall product quality.
A good report communicates:

 What was tested

 What passed/failed

 Reasons for failure

 Environment details

 Execution trends

Interview Tip:
Say: “Our automated reports help stakeholders make go/no-go release decisions confidently.”

Q282. What are the popular reporting tools used in automation frameworks?

Tool Description Key Feature

Extent Reports Rich HTML reports with screenshots, logs Supports interactive charts

Open-source, integrates with TestNG, JUnit, Clean, developer-friendly


Allure Reports
Cucumber design

ReportNG Simple TestNG add-on Lightweight

Cucumber
Built-in for BDD frameworks Scenario-based output
HTML

Interview Tip:
Mention you integrated Extent Reports and Allure Reports with TestNG + Jenkins.

Q283. How do you generate an Extent Report in Selenium framework?


Example:

ExtentReports extent;

ExtentTest test;

@BeforeTest

public void setupReport() {

ExtentSparkReporter spark = new ExtentSparkReporter("Reports/extent.html");

extent = new ExtentReports();

extent.attachReporter(spark);

@Test

public void loginTest() {

test = extent.createTest("Login Test");

test.info("Launching application");

test.pass("Login successful");

@AfterTest

public void tearDown() {

extent.flush();

Interview Tip:
Say: “We added custom logs and screenshots for each failed test step.”

Q284. How do you attach screenshots to reports on test failure?

Example (Extent Report):

public void onTestFailure(ITestResult result) {

String screenshotPath = ScreenshotUtil.capture(driver, result.getName());

test.fail("Test Failed: " + result.getThrowable(),

MediaEntityBuilder.createScreenCaptureFromPath(screenshotPath).build());
}

Screenshot Utility:

public static String capture(WebDriver driver, String name) {

File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

String path = "./Reports/Screenshots/" + name + ".png";

FileUtils.copyFile(src, new File(path));

return path;

Interview Tip:
Explain you automated screenshot capture via TestNG listeners.

Q285. What is Allure Reporting and why is it popular?

Detailed Explanation:
Allure is a lightweight, open-source reporting tool that integrates easily with TestNG, JUnit, and
Cucumber.
It provides:

 Trend graphs

 Attachments (screenshots, logs, JSONs)

 Step-level detail

Command to generate report:

allure serve allure-results

Interview Tip:
Say: “We integrated Allure to visualize API + UI test results together.”

Q286. How can Jenkins be used for test reporting?

Detailed Explanation:
Jenkins automates:

 Test execution

 Report publishing

 Email notifications

Pipeline Example:

stage('Test Execution') {

steps {
sh 'mvn clean test'

stage('Publish Report') {

steps {

publishHTML([reportDir: 'Reports', reportFiles: 'extent.html', reportName: 'Automation Report'])

Interview Tip:
Say you used Jenkins pipelines to run nightly regression and publish reports to Slack/Email.

Q287. How do you track automation test coverage?

Explanation:
Automation coverage = (Automated Test Cases / Total Test Cases) × 100

Tracking Methods:

 Maintain traceability matrix (manual + automated)

 Integrate tools like Zephyr, TestRail, or Azure DevOps


Interview Tip:
Say: “We maintained 85% automation coverage focusing on regression-critical areas.”

Q288. How do you measure automation ROI (Return on Investment)?

Formula:

ROI = (Manual Effort Saved - Automation Effort) / Automation Effort × 100

Example:
If 100 hours manual effort is saved monthly and automation setup took 300 hours:
ROI = (100 × 12 – 300) / 300 = 300%

Interview Tip:
Show that you quantify automation value to justify tool and resource costs.

Q289. What are the key QA metrics you track in automation?

Metric Description

Test Execution Rate % of tests executed in each cycle


Metric Description

Pass Percentage (Tests Passed / Tests Executed) × 100

Defect Density Defects per module size

Defect Leakage Defects found after release

Automation Coverage % of total tests automated

Defect Reopen Rate % of reopened bugs after closure

Interview Tip:
Mention you use dashboards for trend analysis and continuous improvement.

Q290. What is Defect Leakage and how do you minimize it?

Definition:
Defect Leakage = Bugs that escape to later phases (e.g., UAT or Production).

Formula:

Defect Leakage = (Defects found after release / Total defects found) × 100

Minimization Strategies:

 Strong regression suite

 Pair testing

 Root cause analysis

 Test coverage reviews

Interview Tip:
Say: “We reduced leakage by 40% by enhancing automation regression scope.”

Q291. What is a Defect Density metric?

Formula:

Defect Density = Number of Defects / Size of Module (KLOC or Function Points)

Use:
It helps identify high-risk modules requiring more testing or refactoring.

Interview Tip:
Say: “We prioritized testing on high-density modules like Claims Processing in our healthcare
domain.”

Q292. How do you ensure the quality of automated test scripts?


Best Practices:

1. Peer code reviews

2. Linting tools (Checkstyle, SonarLint)

3. Modular and reusable functions

4. Maintain naming conventions

5. Regular refactoring

Interview Tip:
Say you apply code review checklists for all new scripts before merging.

Q293. How do you monitor test results continuously?

Approach:

 Integrate with Jenkins, Grafana, or Kibana dashboards

 Store execution history in a DB or Excel

 Analyze trend graphs weekly

Interview Tip:
Mention continuous monitoring helps detect flaky tests or environment instability early.

Q294. What is a Test Summary Report (TSR)?

Contents:

 Total tests executed

 Passed / Failed count

 Environment details

 Major defects found

 Recommendations

Example:

Test Cycle: Regression 1.2

Total Tests: 500

Passed: 460

Failed: 40

Pass %: 92%

High Defects: 8
Interview Tip:
Say: “We presented TSRs to business teams weekly for transparency.”

Q295. What are Flaky Tests, and how do you handle them?

Definition:
Flaky tests pass or fail inconsistently due to environment instability, timing, or dependencies.

Causes:

 Improper waits

 Dynamic data

 Browser latency

Solutions:

 Add explicit waits

 Stabilize test data

 Retry failed tests

 Separate unstable tests

Interview Tip:
Say you used TestNG retry analyzer to re-run flaky tests automatically.

Q296. How do you track and visualize defects and metrics?

Tools Used:

 JIRA Dashboards

 Power BI / Grafana Reports

 Confluence Metrics Pages

Interview Tip:
Say you built QA dashboards combining test execution trends and defect density graphs.

Q297. How do you handle failed test analysis?

Approach:

1. Analyze logs and screenshots

2. Identify root cause (script issue / app defect / environment)

3. Categorize failures

4. Report valid bugs or fix scripts


Interview Tip:
Say you maintain a failure triage sheet after each regression run.

Q298. What is Continuous Test Monitoring?

Definition:
Continuous monitoring involves tracking test health, failures, and coverage in real time as part of
CI/CD.

Tools:

 Jenkins

 ELK stack

 Grafana dashboards

Interview Tip:
Say continuous monitoring ensures fast feedback loops in Agile pipelines.

Q299. How do you present QA metrics to management?

Techniques:

 Weekly dashboards

 Trend graphs (pass rate, defect density)

 ROI visuals

 Highlight key risks

Interview Tip:
Say: “We used Power BI dashboards linked with Jenkins logs for live reporting.”

Q300. What are your best practices for maintaining test reports and results?

Best Practices:

1. Archive old reports by build version

2. Maintain naming conventions

3. Store reports on shared drives or cloud (S3, GDrive)

4. Include screenshots and logs

5. Automate emailing of summaries

Interview Tip:
Say: “Every Jenkins run emails HTML reports and summary charts to stakeholders automatically.”
Section 17 – Behavioral QA Leadership & STAR-Based Questions (Q301–Q320)

Q301. Tell me about a time you identified a major defect before production.

Situation:
In my healthcare project, I was testing a claims adjudication module before UAT release.

Task:
I noticed a data mismatch between the UI claim summary and backend database — something that
could have impacted billing accuracy.

Action:
I created a data-driven regression script that compared API and database outputs for 100+ claim
records, exposing a rounding logic issue in pricing.

Result:
The defect was fixed before production, avoiding ~$50,000 in billing errors.

Tip:
Show your attention to detail and technical verification beyond UI — it highlights Dive Deep and
Deliver Results.

Q302. Describe a time when you had to deliver results under tight deadlines.

Situation:
We had a 2-day window to validate a hotfix for an integration issue before deployment.

Task:
Automation suite had to be selectively executed and validated overnight.
Action:
I used TestNG groups and Jenkins pipeline triggers to execute only “critical smoke” scenarios and
generated quick reports for sign-off.

Result:
We achieved 100% test completion within the timeline and enabled an on-schedule release.

Tip:
Focus on prioritization and execution speed — a great Deliver Results example.

Q303. Give an example of when you earned the trust of your developers.
Situation:
Developers initially felt QA raised false alarms during API regression testing.
Action:
I started attaching API request/response logs, screenshots, and SQL validations with every defect,
reducing ambiguity.
Result:
Over time, developers began involving QA early in sprint reviews.

Tip:
This reflects Amazon’s principle Earn Trust — show consistency, transparency, and clarity in
communication.

Q304. Tell me about a time when a test failed, and you investigated the root cause.

Situation:
A login test in Jenkins pipeline kept failing randomly.

Action:
I checked logs, identified an intermittent server timeout, and implemented a retry mechanism using
TestNG RetryAnalyzer.

Result:
Failures dropped by 90%.

Tip:
Focus on your debugging mindset and ability to stabilize flaky tests — demonstrates Dive Deep.

Q305. How did you improve a process or framework in your project?

Situation:
Regression runs used to take 4 hours on a single browser.

Action:
I implemented parallel execution using TestNG + Selenium Grid and added browser parameters in
Jenkins jobs.

Result:
Execution time reduced by 60%.

Tip:
Show Invent & Simplify — mention measurable improvement.

Q306. Describe a time you handled a production defect.

Situation:
A production issue in the patient-claims workflow slipped through UAT.
Action:
I led the root-cause analysis, found that an API parameter change wasn’t included in regression tests,
and updated the automation scripts accordingly.

Result:
We prevented similar incidents by integrating API regression with the nightly suite.
Tip:
Demonstrates ownership, accountability, and continuous improvement.

Q307. Give an example of when you had to influence a team decision.

Situation:
The team wanted to use Excel-based test data, but maintenance was high.

Action:
I proposed moving to JSON files with Jackson parser, explaining how it simplifies hierarchical data
handling.

Result:
The team adopted JSON, cutting data maintenance effort by 40%.

Tip:
Shows your technical leadership and ability to guide process improvements.

Q308. Tell me about a time you learned a new tool quickly for a project.

Situation:
We had to start API automation, but no one knew Rest Assured.

Action:
I completed a Udemy certification in a week, built a working prototype, and trained 3 teammates.

Result:
We automated 120 API test cases in the next sprint.

Tip:
Shows Learn and Be Curious — a great Amazon-style example.

Q309. Describe a time when you handled a conflict with a teammate.

Situation:
A teammate disagreed about test priorities during sprint planning.

Action:
I arranged a short sync, used Jira reports to show business impact, and we reprioritized based on
defect severity.

Result:
Sprint testing stayed on schedule without friction.

Tip:
Emphasize collaboration, not confrontation — QA leadership is about negotiation and data-based
decisions.

Q310. Tell me about a time you took ownership of an automation failure.


Situation:
A Jenkins job failed before a client demo because of expired test data.

Action:
I immediately regenerated data, fixed the script, and re-ran the pipeline. Post-demo, I added data
refresh logic before every run.

Result:
Avoided future disruptions and built team trust.

Tip:
Shows Ownership — taking responsibility without excuses.

Q311. Have you ever gone above and beyond your QA role?

Situation:
Developers were overloaded with backend validation tasks.

Action:
I learned SQL queries and automated data verification through JDBC scripts.

Result:
QA turnaround time improved by 30%.
Tip:
Demonstrates initiative — aligns with Bias for Action.

Q312. How do you handle high-severity bugs discovered late in the cycle?

Action Plan:

1. Immediately triage and reproduce the issue

2. Assess business impact

3. Escalate with all evidence (logs, screenshots, data)

4. Conduct RCA post-fix


Example:
In one sprint, a payment gateway issue surfaced during regression; we collaborated with DevOps to
roll back and patch within 4 hours.

Tip:
Shows calm, structured decision-making under pressure.

Q313. Tell me about a time when automation helped your team save effort.

Situation:
Manual smoke testing took 2 hours per build.
Action:
I automated it and integrated with Jenkins.

Result:
Saved ~10 hours per week across sprints.

Tip:
Demonstrate measurable impact — “Saved X hours/week” is powerful.

Q314. How do you handle test cases with unstable environments?

Action Steps:

1. Validate environment health before execution

2. Implement retries

3. Separate flaky tests

4. Use mock APIs when needed


Example:
I created pre-run health checks that skip tests when backend services are down.

Tip:
Shows adaptability and technical control of environments.

Q315. Describe a time you helped mentor a junior tester.

Situation:
A new team member struggled with Selenium locators.

Action:
I conducted short daily mentoring sessions, explained XPath patterns, and paired on exercises.

Result:
Within a month, the tester independently contributed to regression automation.

Tip:
Highlights leadership and coaching mindset.

Q316. Tell me about a situation where testing uncovered a design flaw.

Situation:
During UI testing, I noticed inconsistent validation rules between frontend and backend.

Action:
I raised it as a design issue during sprint review, backed with API data samples.

Result:
The architecture team refactored validation logic for consistency.
Tip:
Shows your system-level thinking — not just testing, but quality ownership.

Q317. Describe how you manage testing in an Agile environment.

Answer:

 Participate in daily stand-ups, backlog grooming, and sprint retrospectives.

 Automate stories in-sprint where possible.

 Maintain a continuous integration cycle with nightly builds.

 Track progress in Jira/Azure DevOps.

Tip:
Say: “We achieved in-sprint automation for 70% of features.”

Q318. How do you balance manual and automation testing?

Approach:

 Automate stable, repetitive flows.

 Keep edge cases and exploratory testing manual.

 Review ROI periodically to decide automation priorities.


Example:
For login, checkout, and API layers — automated; for UI visuals and error handling — manual.

Tip:
Shows strategic QA mindset.

Q319. Tell me about a time when your testing prevented a release failure.

Situation:
During release validation, automation caught a session timeout issue after 15 minutes of inactivity.

Action:
Raised critical bug with steps and logs.
Dev fixed session handling before release.

Result:
Avoided production outage for thousands of users.

Tip:
Show real impact — “prevented customer-facing issue.”

Q320. What motivates you as a QA engineer?


Answer:
“I enjoy improving quality and ensuring smooth user experiences. Automation challenges me to
combine technical skills with creative problem-solving. Seeing my scripts run successfully in CI/CD
and save manual effort motivates me daily.”

Tip:

Section 18 – Agile, Scrum & QA in DevOps Culture (Q321–Q340)

Q321. What is Agile methodology, and why is it important for QA?

Detailed Explanation:
Agile is an iterative software development approach where teams deliver small, incremental
releases frequently. QA plays a continuous role rather than testing at the end.

Benefits for QA:

 Early feedback through continuous testing

 Faster defect detection

 Collaborative delivery

 Improved adaptability to changing requirements

Interview Tip:
Say: “In Agile, QA is embedded from requirement grooming to sprint reviews — not a gatekeeper but
a quality enabler.”

Q322. What is the role of QA in a Scrum team?

QA Responsibilities in Scrum:

1. Participate in sprint planning, backlog refinement, and daily stand-ups.

2. Write acceptance criteria with Product Owners.

3. Develop automation scripts in-sprint.

4. Perform exploratory testing on new features.

5. Support CI/CD pipelines and regression testing.

Interview Tip:
Mention: “We followed the shift-left approach — testing starts as soon as stories are ready for
development.”

Q323. What are Scrum ceremonies and QA’s role in each?


Ceremony Description QA Role

Sprint Planning Define sprint goals Estimate QA effort, clarify test scope

Daily Stand-up 15-min status sync Highlight blockers, report defects

Sprint Review Demonstrate completed stories Validate feature demo

Retrospective Analyze what went well Suggest process & test improvements

Interview Tip:
Say: “I used retrospectives to propose automation coverage tracking.”

Q324. What is the difference between Agile and Waterfall testing?

Aspect Agile Waterfall

Testing Phase Continuous After development

Documentation Lightweight Extensive

Flexibility High Low

QA Involvement Early Late

Feedback Loop Short Long

Interview Tip:
Emphasize collaboration and faster feedback loops in Agile.

Q325. What is the Definition of Done (DoD) and Definition of Ready (DoR)?

Definition of Done (DoD):


A checklist ensuring a story is fully completed before closure — includes development, testing,
documentation, and review.

Definition of Ready (DoR):


Ensures a user story is clear, estimable, and testable before sprint commitment.

Example:
DoD includes — “Code merged, unit tests passed, functional automation executed, defects closed.”

Interview Tip:
Say QA helps define DoD with testing completeness criteria.

Q326. What is a sprint and sprint backlog?

Sprint:
A time-boxed development cycle (usually 2–3 weeks) focused on delivering specific user stories.
Sprint Backlog:
The list of user stories and tasks selected for the sprint, owned by the team.

Interview Tip:
Show understanding of commitment and prioritization in sprint goals.

Q327. How do you ensure in-sprint automation in Agile projects?

Best Practices:

1. Automate stable stories within the same sprint.

2. Use modular, data-driven scripts.

3. Maintain quick smoke suites to validate builds.

4. Integrate automation results into Jenkins.

Interview Tip:
Say: “We maintained a sprint automation ratio of 70%, enabling CI-ready test packs.”

Q328. What is Shift-Left Testing?

Detailed Explanation:
Shift-left means starting testing earlier in the SDLC — during design and development phases.

Benefits:

 Early defect detection

 Cost savings

 Reduced rework

Example:
QA reviews user stories, writes acceptance tests before code is written.

Interview Tip:
Say: “We adopted shift-left by pairing QA with developers during unit test creation.”

Q329. What is Shift-Right Testing?

Detailed Explanation:
Shift-right involves testing in production or near-production environments — focusing on resilience,
performance, and monitoring.

Examples:

 A/B testing

 Chaos engineering

 Production monitoring
Interview Tip:
Say: “We used shift-right to monitor real-time API latency using Grafana and automated health
checks.”

Q330. How do you prioritize testing in Agile?

Approach:

 Focus on business-critical stories first.

 Use risk-based testing.

 Automate repetitive scenarios.

 Keep manual testing for new or complex areas.

Interview Tip:
Say: “We classified user stories by risk and customer impact, focusing automation on the top 20%
critical paths.”

Q331. What is Continuous Integration (CI)?

Definition:
CI ensures that code changes from multiple developers are integrated and tested automatically in a
shared repository.

Tools:
Jenkins, GitHub Actions, Azure DevOps, GitLab CI.

Interview Tip:
Mention you integrated your Selenium/TestNG suite with Jenkins CI pipeline.

Q332. What is Continuous Delivery (CD)?

Definition:
CD automates the deployment of tested builds to staging or production environments, ensuring
quick, safe releases.

Pipeline Example:

Code → Build → Test → Staging → Deploy → Monitor

Interview Tip:
Say: “Our CI/CD pipeline automatically deployed tested builds nightly to the QA environment.”

Q333. What’s the QA role in DevOps?

Responsibilities:

1. Automate test execution in CI/CD pipelines.


2. Validate deployment integrity.

3. Support monitoring and rollback testing.

4. Ensure feedback loops via reporting tools.

Interview Tip:
Say QA bridges Dev and Ops by embedding quality in every stage — from build validation to
production monitoring.

Q334. How does QA ensure collaboration with developers in Agile?

Best Practices:

 Pair testing (QA + Dev)

 Review acceptance criteria together

 Conduct bug triage jointly

 Use shared tools (JIRA, Confluence, Slack)

Interview Tip:
Say: “We introduced QA huddles twice a week to align on blockers and automation targets.”

Q335. How do you measure Agile testing success?

Key Metrics:

 Sprint automation coverage

 Defect leakage

 Story-level pass rate

 Test execution time

 Mean time to detect defects (MTTD)

Interview Tip:
Say: “We tracked sprint defect leakage and aimed for <5%.”

Q336. What are QA’s responsibilities during Sprint Planning?

1. Clarify acceptance criteria

2. Estimate testing and automation effort

3. Identify dependencies (data, environment)

4. Commit to testing deliverables

5. Highlight automation feasibility


Interview Tip:
Say: “QA ensures every story has clear testability criteria before being accepted.”

Q337. How do you handle incomplete stories at sprint end?

Action Steps:

 Move story back to backlog

 Update test cases and status

 Include it in next sprint planning

 Communicate impact to Scrum Master

Interview Tip:
Say: “We avoid partial closures — a story is marked ‘done’ only if automation and manual testing are
complete.”

Q338. What are the challenges of QA in Agile?

Challenge Solution

Frequent requirement changes Use BDD and flexible scripts

Limited testing time Automate regression and use risk-based testing

Environment instability Dockerized test environments

Communication gaps Daily sync-ups and JIRA dashboards

Interview Tip:
Show proactive problem-solving, not just listing challenges.

Q339. How does automation fit into the DevOps pipeline?

Stages Involved:

1. Code Commit: Trigger automation builds.

2. Build Validation: Run smoke tests automatically.

3. Deployment: Run regression suites post-deploy.

4. Monitoring: Execute API health checks periodically.

Interview Tip:
Say you configured Jenkins jobs to trigger Selenium + API tests on every build push.

Q340. What are the best practices for Agile QA automation?


1. Write atomic, independent tests.

2. Implement CI/CD integration.

3. Maintain tagging for test groups (smoke, regression).

4. Keep test data reusable.

5. Pair test automation with exploratory testing.

Interview Tip:
End strong: “Agile QA is not just automation — it’s about enabling faster, safer releases through
collaboration and intelligence.”

Section 19 – QA Leadership & Continuous Improvement Scenarios (Q341–Q360)

Q341. How do you define a test strategy for a new project?

Detailed Explanation:
A test strategy outlines how testing will be performed — defining scope, approach, resources, tools,
and risk mitigation.

Key Components:

1. Scope – Features to be tested

2. Approach – Manual + Automation mix

3. Environment – QA, UAT, staging

4. Tools – Selenium, TestNG, Jenkins, JIRA

5. Metrics – Defect density, coverage

6. Risk Plan – Contingency for blockers

Interview Tip:
Say: “I created a hybrid QA strategy focusing on early automation and parallel test execution for
faster feedback.”

Q342. How do you estimate QA effort for a sprint or release?

Approach:

1. Break stories into tasks (test design, automation, execution).

2. Estimate hours for each task.

3. Add buffer (10–15%) for risks.

4. Validate using past velocity metrics.


Example:
A sprint with 10 stories × 8 hours of testing each = 80 hours + 15% buffer = 92 hours.

Interview Tip:
Show a data-driven mindset — “We used historical story points and defect trends for accurate
estimation.”

Q343. How do you manage testing when requirements are unclear?

Action Plan:

1. Collaborate with Product Owner for clarification.

2. Use exploratory testing to uncover hidden behaviors.

3. Log assumptions in JIRA to maintain transparency.

4. Refine test cases once requirements stabilize.

Interview Tip:
Say: “QA adds value by asking the right questions early — preventing misaligned development.”

Q344. How do you handle high defect leakage post-release?

Root Cause Analysis (RCA):

 Check test coverage gaps

 Review regression suite completeness

 Identify environment mismatches

 Analyze defect categories

Corrective Actions:

 Expand automation coverage

 Strengthen sanity suite

 Introduce peer reviews for test design

Interview Tip:
Say: “We reduced post-release defects by 30% after implementing root cause analysis sessions per
sprint.”

Q345. How do you plan regression testing efficiently?

Steps:

1. Maintain regression suite mapping to modules.

2. Automate stable cases.


3. Use prioritization: P1 (Critical), P2 (High), P3 (Medium).

4. Execute parallel tests with Jenkins pipelines.

Interview Tip:
Say: “Our selective regression reduced execution from 8 hours to 2 hours.”

Q346. What is your approach to handling production incidents?

Action Plan:

1. Analyze incident logs.

2. Reproduce in QA environment.

3. Add automated tests for future prevention.

4. Conduct RCA and update regression packs.


Interview Tip:
Demonstrate calmness and accountability — “Every production bug becomes a new test case in our
regression suite.”

Q347. How do you ensure quality in CI/CD pipelines?

Approach:

 Integrate smoke and sanity tests in the build pipeline.

 Trigger automation on every commit.

 Publish reports via Jenkins/Slack.

 Block deployments if critical tests fail.

Example:

stage('Smoke Tests') {

steps {

sh 'mvn test -Psmoke'

Interview Tip:
Say you used a “quality gate” model in Jenkins for continuous validation.

Q348. How do you communicate test results to stakeholders?

Method:
 Daily stand-up updates

 Weekly QA summary report

 Email dashboards with pass/fail trends

 Highlight business impact defects

Sample Email Snippet:

“Out of 250 regression tests, 243 passed (97%). 2 critical defects logged impacting the billing
workflow.”

Interview Tip:
Shows clarity, confidence, and stakeholder awareness.

Q349. How do you ensure team productivity and motivation?

Approach:

1. Conduct regular knowledge-sharing sessions.

2. Recognize contributions in retrospectives.

3. Rotate members between automation and functional tasks.

4. Use tools like Jira Velocity charts to track throughput.

Interview Tip:
Say: “I believe in mentorship and clear ownership to keep the team engaged.”

Q350. How do you handle defects that developers claim are “not reproducible”?

Approach:

1. Provide detailed logs, screenshots, data IDs.

2. Reproduce with developer on same environment.

3. Compare configurations.

4. Document findings clearly.

Interview Tip:
Show collaboration, not confrontation — “I treat such cases as learning opportunities to improve
environment parity.”

Q351. How do you plan test cases for integration testing?

Strategy:

 Identify module interfaces (API, DB, UI).

 Use real-world workflows.


 Validate data consistency across systems.

 Automate integration flows using Rest Assured or Selenium.

Example:
Order creation → API validation → DB status check → UI confirmation.

Interview Tip:
Say: “We used end-to-end validation combining API + UI automation.”

Q352. How do you handle dependencies between teams (Dev, QA, Ops)?

Approach:

 Track dependencies in Jira.

 Set SLAs for code and environment readiness.

 Use shared Slack channels for communication.

 Escalate blockers early to Scrum Master.

Interview Tip:
Shows ownership and coordination ability in cross-functional teams.

Q353. How do you maintain test documentation efficiently?

Best Practices:

1. Store test cases in Jira or Azure DevOps.

2. Maintain version control for automation scripts in Git.

3. Archive old reports.

4. Document RCA for critical defects.

Interview Tip:
Say: “We used Confluence to maintain living documentation updated every sprint.”

Q354. How do you define QA success metrics for a project?

Metric Description

Defect Leakage Bugs caught post-release

Automation Coverage % of tests automated

Execution Time Efficiency of CI runs

Defect Reopen Rate Quality of testing


Metric Description

Customer Defect Rate External quality indicator

Interview Tip:
Say: “We tracked automation ROI and reduced test cycle time by 50%.”

Q355. What is your approach to continuous improvement in QA?

Steps:

1. Collect sprint metrics.

2. Identify repetitive pain points.

3. Suggest automation/process changes.

4. Track improvement over time.

Example:
Reduced flaky tests by stabilizing waits and reusing driver utilities.

Interview Tip:
Show your mindset of Inspect and Adapt.

Q356. How do you handle cross-browser and cross-platform testing?

Approach:

 Use Selenium Grid, BrowserStack, or Dockerized Selenium.

 Maintain browser compatibility matrix.

 Parameterize browsers in TestNG XML.

Example:

<parameter name="browser" value="chrome"/>

Interview Tip:
Say: “We automated browser validation across Chrome, Firefox, and Edge in Jenkins CI.”

Q357. How do you ensure test data consistency?

Approach:

 Use data seeding scripts or mock APIs.

 Isolate environment data per test.

 Mask sensitive data for compliance (HIPAA, GDPR).

 Refresh data regularly from production snapshots.


Interview Tip:
Say: “We built a test data factory that generates dynamic inputs before execution.”

Q358. How do you ensure security and compliance in QA?

Best Practices:

 Mask PHI/PII data.

 Follow OWASP top 10 testing guidelines.

 Integrate security scans in CI (SonarQube, ZAP).

 Enforce secure credential storage.

Interview Tip:
Especially in healthcare domain, emphasize HIPAA and data privacy awareness.

Q359. What is your approach to test environment management?

Strategy:

 Maintain environment matrix (Dev, QA, UAT).

 Automate environment health checks.

 Use Docker for isolated test setups.

 Monitor build versions per environment.

Interview Tip:
Say: “We used Jenkins jobs to auto-verify environment readiness before test execution.”

Q360. How do you see the future of automation testing?

Answer:
Automation is evolving toward intelligent, integrated testing — combining AI, cloud, and continuous
validation.
Key trends:

 AI-driven locators (Healenium, Testim)

 Low-code automation (Tosca, Katalon)

 Self-healing frameworks

 End-to-end CI/CD integration

Interview Tip:
End powerfully: “The future QA engineer is not just a tester — but a quality engineer who ensures
product excellence at every stage.”

You might also like