Automation Testing Interview Q&A Guide
Comprehensive guide for Selenium WebDriver, Java, Cucumber, and Mobile Automation interviews.
Selenium Fundamentals
1. What is Selenium WebDriver?
English: An open-source API that allows programmatic
interaction with web browsers to automate UI testing.
Hinglish: Selenium WebDriver browser ko automatically chalane aur UI test karne ka ek tool hai.
Hinglish: Selenium WebDriver browser ko automatically chalane aur UI test karne ka ek tool hai.
2. Why is ID locator preferred over others?
English: IDs are generally unique in a DOM and are indexed
by the browser, making them the fastest and most reliable locator.
Hinglish: ID unique hoti hai isliye browser use jaldi dhoond leta hai aur ye sabse fast locator hai.
Hinglish: ID unique hoti hai isliye browser use jaldi dhoond leta hai aur ye sabse fast locator hai.
3. Difference between / and // in XPath?
English: / (Single Slash): Relative path
starting from the immediate parent. // (Double Slash): Absolute path
searching the whole DOM for a matching node.
Hinglish: / matlab shuruat se ek-ek step; // matlab poore page pe kahi bhi matching item dhoondhna.
Hinglish: / matlab shuruat se ek-ek step; // matlab poore page pe kahi bhi matching item dhoondhna.
4. What is the difference between Implicit Wait and Explicit Wait?
English: Implicit: Applied globally to all
elements. Explicit: Applied to a specific element for a specific condition
(visibility/clickability).
Hinglish: Implicit pure browser ke liye, Explicit sirf ek khas item ki condition ke liye.
Hinglish: Implicit pure browser ke liye, Explicit sirf ek khas item ki condition ke liye.
5. How to handle multiple windows in Selenium?
English: Using
Hinglish: Saare windows ki IDs lekar, loop chala kar, driver ko switch() karna padta hai.
getWindowHandles() to get a set
of unique IDs, then iterating through them and using
switchTo().window(handle).Hinglish: Saare windows ki IDs lekar, loop chala kar, driver ko switch() karna padta hai.
6. What is specific about findElements() return type?
English: It returns a
Hinglish: Ye matching items ki puri list deta hai aur kuch na mile toh khali list return karta hai (error nahi aata).
List<WebElement>.
If no elements are found, it returns an empty list instead of throwing an exception.Hinglish: Ye matching items ki puri list deta hai aur kuch na mile toh khali list return karta hai (error nahi aata).
7. What are CSS Selectors and why use them?
English: CSS Selectors are patterns used to select elements
for styling. In Selenium, they are faster than XPath in many browsers (like Chrome/IE).
Hinglish: CSS Selectors styling ke liye hote hain par Selenium mein ye XPath se fast kaam karte hain.
Hinglish: CSS Selectors styling ke liye hote hain par Selenium mein ye XPath se fast kaam karte hain.
8. How to handle alert popups in Selenium?
English: Using
Hinglish: Simple alert ke liye switchTo().alert() use karke accept ya dismiss karte hain. Practice Alert Handling in Lab
Alert alert = driver.switchTo().alert(); then alert.accept() or
alert.dismiss().Hinglish: Simple alert ke liye switchTo().alert() use karke accept ya dismiss karte hain. Practice Alert Handling in Lab
Intermediate & Advanced Automation
9. What is 'StaleElementReferenceException'?
English: Occurs when an element that was found earlier is no
longer in the DOM (e.g., due to a page refresh).
Hinglish: Jab page refresh ho jaye aur purana element ka zariya (reference) khatam ho jaye.
Hinglish: Jab page refresh ho jaye aur purana element ka zariya (reference) khatam ho jaye.
10. How to perform mouse hover or drag-and-drop actions?
English: Using the Actions class:
Hinglish: Mouse hover ya drag-drop ke liye Actions class ka use karke perform() lagana padta hai. Practice Mouse Actions in Lab
actions.moveToElement(el).perform() for hover and
actions.dragAndDrop(src, dest).perform() for drag.Hinglish: Mouse hover ya drag-drop ke liye Actions class ka use karke perform() lagana padta hai. Practice Mouse Actions in Lab
11. What is JavaScriptExecutor and common use cases?
English: Interface to run JS code. Used for scrolling,
clicking hidden elements, or handling tricky UI when Selenium fails.
Hinglish: Browser mein direct JS chalane ke liye; jaise invisible items click karna ya page scroll karna.
Hinglish: Browser mein direct JS chalane ke liye; jaise invisible items click karna ya page scroll karna.
12. How to handle Frames (iframes) in Selenium?
English: Using
Hinglish: switchTo().frame() se andar jaate hain aur defaultContent() se wapas bahar main page par.
driver.switchTo().frame(index/name/element). To return, use
driver.switchTo().defaultContent().Hinglish: switchTo().frame() se andar jaate hain aur defaultContent() se wapas bahar main page par.
13. Explain Page Object Model (POM).
English: A design pattern where each page is a class
containing its own elements (locators) and actions (methods). Increases reusability.
Hinglish: Har web page ki alag class banana aur usme uske saare buttons/logic rakhna, taaki code manage karna aasan ho.
Hinglish: Har web page ki alag class banana aur usme uske saare buttons/logic rakhna, taaki code manage karna aasan ho.
14. What is Page Factory?
English: An extension of POM in Selenium that uses
Hinglish: POM ka advanced version jisme @FindBy annotations se items dhoondhe aur manage kiye jaate hain.
@FindBy annotations to initialize web elements lazily.Hinglish: POM ka advanced version jisme @FindBy annotations se items dhoondhe aur manage kiye jaate hain.
15. How to handle synchronization issues in Selenium?
English: Using various Waits: Implicit, Explicit, and Fluent
Wait to sync the code speed with browser speed.
Hinglish: Browser aur script ki speed match karne ke liye alag-alag waits use karna.
Hinglish: Browser aur script ki speed match karne ke liye alag-alag waits use karna.
16. How to take a screenshot only of a specific element? (Selenium 4)
English:
Hinglish: Selenium 4 se hum kisi ek khas button ya image ka screenshot le sakte hain bina poore page ke.
element.getScreenshotAs(OutputType.FILE); available in Selenium 4.Hinglish: Selenium 4 se hum kisi ek khas button ya image ka screenshot le sakte hain bina poore page ke.
๐ Frameworks & BDD (TestNG, Cucumber)
17. Difference between Soft Assert and Hard Assert in TestNG?
English: Hard Assert: Stops test execution
immediately on failure. Soft Assert: Continues execution and reports
failures at the end.
Hinglish: Hard assert test ko turant rok deta hai, Soft assert sare checks karke last mein result deta hai.
Hinglish: Hard assert test ko turant rok deta hai, Soft assert sare checks karke last mein result deta hai.
18. What are TestNG Annotations sequence?
English: @BeforeSuite -> @BeforeTest -> @BeforeClass ->
@BeforeMethod -> @Test -> @AfterMethod...
Hinglish: Suite se lekar Test level tak ke sequential annotations hain jo framework ka flow control karte hain.
Hinglish: Suite se lekar Test level tak ke sequential annotations hain jo framework ka flow control karte hain.
19. What is Cucumber and Gherkin?
English: Cucumber: A BDD tool.
Gherkin: The language used (Given, When, Then) to write tests in plain
English.
Hinglish: Cucumber ek tool hai jo simple English (Gherkin) mein likhe tests ko code se jodta hai.
Hinglish: Cucumber ek tool hai jo simple English (Gherkin) mein likhe tests ko code se jodta hai.
20. What is a 'Scenario Outline' in Cucumber?
English: Used to run the same scenario multiple times with
different sets of data using an
Hinglish: Ek hi scenario ko alag-alag data sets ke saath baar-baar chalane ka tareeka.
Examples: table.Hinglish: Ek hi scenario ko alag-alag data sets ke saath baar-baar chalane ka tareeka.
21. Purpose of `testng.xml` file?
English: Configuration file to define suites, tests,
parallel execution, parameters, and listeners.
Hinglish: Is file se hum poore testing suite ka behavior control karte hain (like parallel running).
Hinglish: Is file se hum poore testing suite ka behavior control karte hain (like parallel running).
22. What is a DataProvider in TestNG?
English: A way to pass multiple sets of data to a single
test method for data-driven testing.
Hinglish: Ek hi test ko alag-alag values se baar-baar chalane ke liye data provider use hota hai.
Hinglish: Ek hi test ko alag-alag values se baar-baar chalane ke liye data provider use hota hai.
23. How to achieve parallel execution in TestNG?
English: By setting
Hinglish: testng.xml mein attributes badal kar hum ek saath kai tests chala sakte hain.
parallel="methods" or
parallel="tests" in testng.xml.Hinglish: testng.xml mein attributes badal kar hum ek saath kai tests chala sakte hain.
๐ Java for Automation (Core Concepts)
24. Difference between Method Overloading and Overriding?
English: Overloading: Same method name,
different parameters (static/compile-time). Overriding: Same method
signature in parent and child class (dynamic/run-time).
Hinglish: Overloading ek hi class mein parameters badalkar hoti hai; Overriding tab jab child class parent ka function badalti hai.
Hinglish: Overloading ek hi class mein parameters badalkar hoti hai; Overriding tab jab child class parent ka function badalti hai.
25. Explain Exception Handling in Java.
English: Using try, catch, finally, throw, and throws to
handle runtime errors gracefully.
Hinglish: Program mein koi error aaye toh use try-catch se handle karna taaki crash na ho.
Hinglish: Program mein koi error aaye toh use try-catch se handle karna taaki crash na ho.
26. What is a 'static' keyword in Java?
English: Means the member belongs to the class rather than
an instance. Shared across all objects.
Hinglish: static ka matlab wo cheez class ki hai, kisi specific object ki nahi (har jagah shared rahegi).
Hinglish: static ka matlab wo cheez class ki hai, kisi specific object ki nahi (har jagah shared rahegi).
27. Difference between ArrayList and LinkedList?
English: ArrayList: Faster for retrieval
(random access). LinkedList: Faster for insertion and deletion.
Hinglish: ArrayList se data nikalna fast hai; LinkedList mein data beech mein daalna/hatana fast hai.
Hinglish: ArrayList se data nikalna fast hai; LinkedList mein data beech mein daalna/hatana fast hai.
28. What is Interface in Java?
English: A blueprint of a class that can contain only method
signatures and constant variables. Achieves 100% abstraction.
Hinglish: Ek 'shart' ya blueprint jo batata hai class mein kya hona chaiye (WebDriver khud ek interface hai).
Hinglish: Ek 'shart' ya blueprint jo batata hai class mein kya hona chaiye (WebDriver khud ek interface hai).
29. Why Java is not purely Object Oriented?
English: Because it uses primitive data types like int,
char, boolean which are not objects.
Hinglish: Kyuki Java mein int, char jaise variables objects nahi hote.
Hinglish: Kyuki Java mein int, char jaise variables objects nahi hote.
๐ CI/CD & Mobile Automation
30. What is Maven and its benefits?
English: A build automation tool used to manage dependencies
(jars), project lifecycle, and reporting via
Hinglish: Maven libraries (jars) manage karne aur build automatic banane ka tool hai.
pom.xml.Hinglish: Maven libraries (jars) manage karne aur build automatic banane ka tool hai.
31. Role of Jenkins in Automation?
English: A CI tool used to trigger automation suites
automatically on every code commit or on a schedule (nightly builds).
Hinglish: Jenkins automatic test chalane aur report bhejne ke liye pipeline banata hai.
Hinglish: Jenkins automatic test chalane aur report bhejne ke liye pipeline banata hai.
32. What is Git and common commands?
English: Version control system. Commands:
Hinglish: Code ke badlav track karne ke liye; push, commit, pull iske main commands hain.
git add, git commit, git push, git pull,
git merge.Hinglish: Code ke badlav track karne ke liye; push, commit, pull iske main commands hain.
33. How Appium differs from Selenium?
English: Selenium is for Web; Appium is for Mobile
(Android/iOS). Appium acts as a wrapper for native automation engines.
Hinglish: Selenium websites ke liye hai, aur Appium mobile apps (Android/iOS) ke liye.
Hinglish: Selenium websites ke liye hai, aur Appium mobile apps (Android/iOS) ke liye.
34. What is 'Desired Capabilities' in Appium?
English: JSON object sent to the server to define the
device, OS, app path, and automation engine.
Hinglish: Appium ko batane ke liye ki kaunsa phone aur kaunsi app test karni hai.
Hinglish: Appium ko batane ke liye ki kaunsa phone aur kaunsi app test karni hai.
35. What is Headless browser testing?
English: Running browser tests without a visible UI. Faster
and consumes less resources. Used in CI/CD.
Hinglish: Bina kisi window dikhaye piche (background) tests chalana, jo fast hota hai.
Hinglish: Bina kisi window dikhaye piche (background) tests chalana, jo fast hota hai.
36. How to find a broken link in Selenium?
English: Collect all
Hinglish: Saare links ke URLs nikaal kar check karna ki koi page dead toh nahi hai (e.g., 404 error).
<a> tags, get
'href', and check HTTP response codes using HttpURLConnection (200=OK,
404=Broken).Hinglish: Saare links ke URLs nikaal kar check karna ki koi page dead toh nahi hai (e.g., 404 error).
๐ Scenario Based & Coding Qs
37. How to handle a dynamic table in Selenium?
English: Iterate through
Hinglish: Table ki rows aur columns pe loop chala kar data verify karna.
<tr> and
<td> tags using loops to find or verify specific cell data.Hinglish: Table ki rows aur columns pe loop chala kar data verify karna.
38. What is the difference between '/' and '//' in relative Xpath? (Revisited)
English: Single slash (/) looks for internal child, while
double slash (//) looks anywhere in the sub-tree.
Hinglish: / matlab sirf uska bacha; // matlab bacha, pota, poore tree mein kahi bhi.
Hinglish: / matlab sirf uska bacha; // matlab bacha, pota, poore tree mein kahi bhi.
39. How to verify a tooltip in Selenium?
English: Hover over the element and get the
Hinglish: Mouse hover karke 'title' attribute ka text read karna.
title attribute using getAttribute("title").Hinglish: Mouse hover karke 'title' attribute ka text read karna.
40. How to handle cookies in Selenium?
English: Using
Hinglish: Browser ki cookies set karna ya saaf karne ke liye manage() commands.
driver.manage().getCookies(),
addCookie(), or deleteAllCookies().Hinglish: Browser ki cookies set karna ya saaf karne ke liye manage() commands.
41. What is the use of `fluentWait`?
English: It's a type of Explicit wait where you can define
the polling frequency and ignore specific exceptions (like NoSuchElementException).
Hinglish: Ye wait har thodi der (polling) mein check karta hai ki item aya ya nahi, error chhodkar.
Hinglish: Ye wait har thodi der (polling) mein check karta hai ki item aya ya nahi, error chhodkar.
42. How to handle SVG elements in Selenium?
English: By using special XPath tag
Hinglish: SVG icons graphics hote hain isliye unhe local-name() waale XPath se dhoondhte hain.
//*[local-name()='svg'].Hinglish: SVG icons graphics hote hain isliye unhe local-name() waale XPath se dhoondhte hain.
43. How to maximize the browser window?
English:
Hinglish: Browser ki screen badi karne ke liye maximize() use karte hain.
driver.manage().window().maximize();Hinglish: Browser ki screen badi karne ke liye maximize() use karte hain.
44. How to click on a radio button?
English: Identify the element by ID or XPath and use
Hinglish: Radio button ka locator dhoondh kar bas click() command chalana hai.
.click().Hinglish: Radio button ka locator dhoondh kar bas click() command chalana hai.
45. Can we automate Desktop Applications with Selenium?
English: No, Selenium is strictly for Web Applications. Use
tools like WinAppDriver or AutoIT for Desktop apps.
Hinglish: Nahi, Selenium sirf websites ke liye hai.
Hinglish: Nahi, Selenium sirf websites ke liye hai.
46. What is shadow DOM and how to handle it?
English: Encapsulated DOM inside another DOM. Handle it
using
Hinglish: Ye DOM ke andar ek chupa hua DOM hota hai jise access karne ke liye getShadowRoot() lagta hai.
element.getShadowRoot() (Selenium 4).Hinglish: Ye DOM ke andar ek chupa hua DOM hota hai jise access karne ke liye getShadowRoot() lagta hai.
47. Relationship between Selenium and WebDriver?
English: Selenium is the suite name. WebDriver is a
component of Selenium that provides the direct communication API with browsers.
Hinglish: Selenium poora ghar hai, aur WebDriver us ghar ka ek mukhya kamra (main tool).
Hinglish: Selenium poora ghar hai, aur WebDriver us ghar ka ek mukhya kamra (main tool).
48. What is `driver.navigate().to()` vs `driver.get()`?
English: Both open a URL.
Hinglish: Dono URL kholte hain, par navigate() mein back/forward/refresh karne ke options hote hain.
navigate() maintains
history and supports back(), forward(),
refresh().Hinglish: Dono URL kholte hain, par navigate() mein back/forward/refresh karne ke options hote hain.
49. What is continuous testing?
English: The process of executing automated tests as part of
the software delivery pipeline to obtain immediate feedback.
Hinglish: Code badalte hi turant automation chalana taaki fauran feedback mil sake.
Hinglish: Code badalte hi turant automation chalana taaki fauran feedback mil sake.
50. How to scroll up/down using Selenium?
English:
Hinglish: JavaScriptExecutor ki madad se page niche scroll karna.
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");Hinglish: JavaScriptExecutor ki madad se page niche scroll karna.
51. What is CDP in Selenium 4?
English: Chrome DevTools Protocol. Allows you to set network
conditions, capture console logs, and simulate geolocations.
Hinglish: Selenium 4 ka feature jo browser ke advanced settings (jaise slow internet) control karta hai.
Hinglish: Selenium 4 ka feature jo browser ke advanced settings (jaise slow internet) control karta hai.
52. How to handle multiple checkboxes in one go?
English: Find them using
Hinglish: Saare boxes ko ek list mein la kar for-loop se tick karna.
findElements() with a
common locator and iterate through the list to click each.Hinglish: Saare boxes ko ek list mein la kar for-loop se tick karna.
53. What is Parallelism in Selenium Grid?
English: The ability to execute multiple tests across
various nodes (different browser-machine combos) simultaneously.
Hinglish: Ek saath alag-alag machines pe tests chalane ki kshamta.
Hinglish: Ek saath alag-alag machines pe tests chalane ki kshamta.
54. Name some reports used in Automation.
English: Extent Reports, Allure Reports, TestNG HTML
Reports, and Cucumber JVM Reports.
Hinglish: Results dikhane ke liye Reports (เคเฅเคธเฅ Extent, Allure) use hote hain.
Hinglish: Results dikhane ke liye Reports (เคเฅเคธเฅ Extent, Allure) use hote hain.
55. How to handle Drag and Drop? (Alternative way)
English: Use
Hinglish: Item pakad kar, move karke, phir chhodne waale steps (manual feel).
clickAndHold(source),
moveToElement(target), then release().Hinglish: Item pakad kar, move karke, phir chhodne waale steps (manual feel).
๐ Automation Testing (Selenium, Framework & Scenarios)
1. What is Selenium?
English: Selenium is an open-source automation testing tool
used to automate web applications across different browsers such as Chrome, Firefox, and
Edge.
Hinglish: Selenium ek open-source automation tool hai jo web applications ko automate karne ke liye use hota hai.
Hinglish: Selenium ek open-source automation tool hai jo web applications ko automate karne ke liye use hota hai.
2. What are the components of Selenium?
English: Selenium has four main components:
- Selenium IDE: Record and playback tool
- Selenium WebDriver: Automates browsers using programming languages
- Selenium Grid: Runs tests on multiple machines and browsers
- Selenium RC: Older version (now deprecated)
Hinglish: Selenium ke 4 main components hote hain: IDE, WebDriver, Grid, aur RC.
- Selenium IDE: Record and playback tool
- Selenium WebDriver: Automates browsers using programming languages
- Selenium Grid: Runs tests on multiple machines and browsers
- Selenium RC: Older version (now deprecated)
Hinglish: Selenium ke 4 main components hote hain: IDE, WebDriver, Grid, aur RC.
3. What is WebDriver in Selenium?
English: Selenium WebDriver is an API that allows testers to
interact with web browsers and automate user actions like clicking, typing, and
navigating.
Hinglish: WebDriver ek API hai jo browser ko control karke automation perform karta hai.
Hinglish: WebDriver ek API hai jo browser ko control karke automation perform karta hai.
4. What are locators in Selenium?
English: Locators are used to identify web elements on a
webpage. Common locators: ID, Name, Class Name, XPath, CSS Selector, Tag Name, and Link
Text.
Hinglish: Locators ka use web elements ko find karne ke liye hota hai.
Hinglish: Locators ka use web elements ko find karne ke liye hota hai.
5. What is XPath in Selenium?
English: XPath is a locator used to find elements in an HTML
DOM structure.
Hinglish: XPath ek path expression hai jo HTML structure me element locate karta hai.
driver.findElement(By.xpath("//input[@id='username']"));Hinglish: XPath ek path expression hai jo HTML structure me element locate karta hai.
6. Difference between Absolute and Relative XPath?
English:
- Absolute XPath: Starts from the root node (/html/body/...). Highly unstable as any small UI change breaks it.
- Relative XPath: Starts from anywhere in the DOM (//tagname[@attr='value']). More stable and widely used.
Hinglish:
- Absolute: Root se start hota hai, thoda change hone par break ho jata hai.
- Relative: Beech se start kar sakte hain, zyada reliable hota hai.
- Absolute XPath: Starts from the root node (/html/body/...). Highly unstable as any small UI change breaks it.
- Relative XPath: Starts from anywhere in the DOM (//tagname[@attr='value']). More stable and widely used.
Hinglish:
- Absolute: Root se start hota hai, thoda change hone par break ho jata hai.
- Relative: Beech se start kar sakte hain, zyada reliable hota hai.
7. How to handle dropdowns in Selenium?
English: We use the Select class for static
dropdowns.
Select sel = new Select(element);
sel.selectByVisibleText("Option");
Hinglish: Dropdowns handle karne ke liye Select
class ka use hota hai.
8. What is Fluent Wait in Selenium?
English: Fluent Wait is used to wait for an element with a
specific frequency and can ignore specific exceptions (like NoSuchElementException) during
the polling period.
Hinglish: Fluent Wait har thodi der (polling) me element check karta hai aur error skip kar sakta hai.
Hinglish: Fluent Wait har thodi der (polling) me element check karta hai aur error skip kar sakta hai.
9. What is the difference between driver.close() and driver.quit()?
English:
- driver.close(): Closes the current browser window/tab that Selenium is currently controlling.
- driver.quit(): Closes all browser windows and tabs associated with the WebDriver session and ends the session.
Hinglish:
- close(): current tab close karta hai
- quit(): poora browser aur session close karta hai
- driver.close(): Closes the current browser window/tab that Selenium is currently controlling.
- driver.quit(): Closes all browser windows and tabs associated with the WebDriver session and ends the session.
Hinglish:
- close(): current tab close karta hai
- quit(): poora browser aur session close karta hai
10. Difference between implicit and explicit waits & Why do we use waits?
English: We use waits in Selenium to handle synchronization
between Selenium and web elements. It helps Selenium wait until the element is visible or
clickable.
Syntax for Explicit Wait:
| Feature | Implicit Wait | Explicit Wait |
|---|---|---|
| Scope | Global (All elements) | Local (Specific element) |
| Condition | Presence in DOM | Specific conditions (Visibility, Clickable) |
Syntax for Explicit Wait:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("loginBtn")));
Hinglish: Selenium me waits ka use synchronization
ke liye hota hai, taaki Selenium tab tak wait kare jab tak element visible ya clickable na
ho.
11. Write an XPath for an element and a dynamic table.
English:
- Standard element:
- Dynamic Table:
Hinglish:
- Standard: Yeh XPath ID ke through element locate karta hai.
- Dynamic Table: Yeh table ke particular row aur column ka data find karta hai.
- Standard element:
//input[@id='username'] - Locates an input
box using its ID.- Dynamic Table:
//table[@id='empTable']//tr[2]/td[3] - Finds
data from a specific row and column.Hinglish:
- Standard: Yeh XPath ID ke through element locate karta hai.
- Dynamic Table: Yeh table ke particular row aur column ka data find karta hai.
12. What is an exception in Selenium and what have you faced?
English: An exception is an unwanted situation that occurs
during execution and stops normal flow. Common facing exceptions:
- NoSuchElementException: Element locator is wrong or element is not on page.
- ElementNotInteractableException: Element is hidden or disabled.
- StaleElementReferenceException: Page refreshed after element was found.
- TimeoutException: Wait time exceeded before element appeared.
Hinglish: Exception ek unwanted situation hoti hai jo flow ko stop kar deti hai. Common: Element na mile, refresh ke baad error, wait timeout error.
- NoSuchElementException: Element locator is wrong or element is not on page.
- ElementNotInteractableException: Element is hidden or disabled.
- StaleElementReferenceException: Page refreshed after element was found.
- TimeoutException: Wait time exceeded before element appeared.
Hinglish: Exception ek unwanted situation hoti hai jo flow ko stop kar deti hai. Common: Element na mile, refresh ke baad error, wait timeout error.
13. Difference between findElement() vs findElements().
English:
- findElement(): Returns single element, throws NoSuchElementException if not found.
- findElements(): Returns list of elements, returns empty list if not found.
Hinglish: findElement() ek element deta hai (error if not found), findElements() list deta hai (empty if not found).
- findElement(): Returns single element, throws NoSuchElementException if not found.
- findElements(): Returns list of elements, returns empty list if not found.
Hinglish: findElement() ek element deta hai (error if not found), findElements() list deta hai (empty if not found).
14. How to handle alerts in Selenium?
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept(); // click OK
alert.dismiss(); // click Cancel
alert.sendKeys("text"); // enter text
15. Write the syntax for wait and take a screenshot.
English: This waits for an element and then takes a
screenshot.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("logo")));
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("screenshot.png"));
Hinglish: Yeh pehle element ke visible hone ka wait
karta hai aur phir screenshot leta hai.
16. How do you design a POM (Page Object Model) framework?
English: POM means each web page has its own class
containing Locators (WebElements) and Actions/Methods. Test cases are kept separate.
Hinglish: POM follow karne se code maintainable, reusable, aur clean banta hai.
Architecture Example:
Hinglish: POM follow karne se code maintainable, reusable, aur clean banta hai.
Architecture Example:
src/test/java
โโโ pages
โ โโโ LoginPage.java (Locators & login())
โ โโโ HomePage.java (Locators & logout())
โโโ tests
โ โโโ LoginTest.java (Calls LoginPage methods)
โโโ base
โโโ BaseTest.java (Driver setup & teardown)
17. How do you handle the 4th tab when multiple browser tabs are opened?
English: We collect all window handles, convert them to a
list, and switch using the index.
Set<String> handles = driver.getWindowHandles(); List<String> tabs = new ArrayList<>(handles); driver.switchTo().window(tabs.get(3)); // index 3 = 4th tabHinglish: Hum window handles ko list me store karke required tab ke index par switch karte hain.
18. How would you resolve StaleElementException?
English: StaleElementException happens when the element is
refreshed or reloaded. Solution: Re-locate the element again.
Hinglish: Page refresh hone ke baad element dobara find (re-locate) karo.
Hinglish: Page refresh hone ke baad element dobara find (re-locate) karo.
19. Explain your roles and responsibilities.
English: "My roles include analyzing requirements, writing
test cases/scripts, executing tests, logging defects, performing regression testing, and
CI/CD integration using Jenkins."
Hindi: "Meri responsibilities hain requirements analyze karna, test cases/scripts likhna, bugs log karna, aur Jenkins ke saath integration karna."
Hindi: "Meri responsibilities hain requirements analyze karna, test cases/scripts likhna, bugs log karna, aur Jenkins ke saath integration karna."
20. Explain your automation project / framework.
English: Developed using Selenium, Java, and TestNG with
POM. Includes Base class (setup), Page classes (locators), Test classes (execution), and
Utils (reports, screenshots).
Hinglish: Mera project Selenium, Java aur TestNG par based hai. Hum POM follow karte hain aur Extent Reports use karte hain.
Main Components:
Hinglish: Mera project Selenium, Java aur TestNG par based hai. Hum POM follow karte hain aur Extent Reports use karte hain.
Main Components:
- Base Class: Driver setup, browser config, waits.
- Page Classes: Locators and reusable methods.
- Test Classes: Actual test steps.
- Utility Classes: Screenshot, Excel, and Logs.
21. How do you handle iframes in Selenium?
English: You must switch to an iframe before interacting
with its elements. Use index, name/ID, or WebElement.
driver.switchTo().frame("id"); // Switch In
driver.switchTo().defaultContent(); // Switch Out
Hinglish: Iframe ke andar jaane ke liye
switchTo().frame() aur bahar aane ke liye defaultContent() use karte hain.
22. Hard Assert vs Soft Assert in TestNG?
English:
- Hard Assert: Stops execution immediately on failure. (
- Soft Assert: Execution continues; report failures at the end using
Hinglish: Hard assert fail hone par test wahi ruk jata hai. Soft assert fail hone par bhi baaki code chalta hai.
- Hard Assert: Stops execution immediately on failure. (
Assert.assertEquals)- Soft Assert: Execution continues; report failures at the end using
assertAll().Hinglish: Hard assert fail hone par test wahi ruk jata hai. Soft assert fail hone par bhi baaki code chalta hai.
23. How to scroll down to a particular element in Selenium?
English: Best method is using
JavaScriptExecutor with
scrollIntoView(true).WebElement element = driver.findElement(By.id("btn"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Hinglish: JavaScriptExecutor se page ko kisi unit
element tak scroll kara sakte hain.
24. What is Drag and Drop in Selenium and how do you perform it?
English: Pick an element, hold it, drag it over another, and
drop it. We use the Actions class in Selenium for this.
Hinglish: Ek element ko click karke pakadna (drag) aur dusre element par chhod dena (drop).
Drag and Drop Code:
Hinglish: Ek element ko click karke pakadna (drag) aur dusre element par chhod dena (drop).
Drag and Drop Code:
WebElement source = driver.findElement(By.id("draggable"));
WebElement target = driver.findElement(By.id("droppable"));
Actions act = new Actions(driver);
act.dragAndDrop(source, target).perform();
25. How do you handle (manage) Alerts in Selenium?
English: An Alert is a JavaScript pop-up. Selenium cannot
inspect it directly, so we use the Alert interface.
Hinglish: Alert ek JS browser popup hota hai jise inspect nahi kar sakte, hume
Types of Alerts:
Hinglish: Alert ek JS browser popup hota hai jise inspect nahi kar sakte, hume
driver.switchTo().alert() use karna padta
hai.Types of Alerts:
- Simple Alert: Only OK button
- Confirmation Alert: OK & Cancel buttons
- Prompt Alert: Textbox + OK/Cancel
Alert alert = driver.switchTo().alert();
alert.accept(); // Click OK
alert.dismiss(); // Click Cancel
System.out.println(alert.getText()); // Read message
alert.sendKeys("Hello"); // Send text to prompt
26. What is Page Factory Concept in Selenium (Using Java)?
English: Page Factory is a design pattern in Selenium used
to initialize web elements of a page using
Hinglish: Page Factory Selenium ka ek design pattern hai jo web elements ko
Why use Page Factory?
@FindBy annotations. It is an
advanced way of implementing Page Object Model (POM).Hinglish: Page Factory Selenium ka ek design pattern hai jo web elements ko
@FindBy annotation se initialize karta
hai.Why use Page Factory?
- Reduces code duplication: Minimal element initialization.
- Improves readability: Clear separation of locators.
- Easy Locators: Locators are managed within annotations.
27. Explain the order of TestNG annotations.
English: The execution order runs from Suite to Method and
back.
Hinglish: TestNG annotations ka order
Execution Order:
Hinglish: TestNG annotations ka order
@BeforeSuite se start hota hai aur @AfterSuite par end hota
hai.Execution Order:
@BeforeSuite โ @BeforeTest โ @BeforeClass โ @BeforeMethod
โ
@Test
โ
@AfterMethod โ @AfterClass โ @AfterTest โ @AfterSuite
28. What are XPath Axes? Give examples.
English: XPath Axes are used to locate elements based on
their relationship with other elements. Examples: parent, child, following-sibling,
preceding-sibling, ancestor, descendant.
Hinglish: XPath Axes element ko relation ke basis par locate karta hai jaise parent-child.
Examples:
Hinglish: XPath Axes element ko relation ke basis par locate karta hai jaise parent-child.
Examples:
//input[@id='email']/parent::div//label[text()='Username']/following-sibling::input
29. What is the Difference Between Cucumber and TestNG?
| Feature | Cucumber | TestNG |
|---|---|---|
| Approach | BDD | TDD |
| Language | Gherkin (Plain English) | Java |
| Usage | Acceptance Testing | Functional/Unit Testing |
English: Cucumber is used for behavior-based testing using plain English, whereas TestNG is used for structured execution and reporting.
Hinglish: Cucumber collaboration ke liye best hai, TestNG complex logic ke liye use hota hai.
30. What is Given, When, Then?
English: Given, When, Then is a BDD (Behavior Driven
Development) format used in Cucumber.
Hinglish: Given, When, Then BDD format hai jo Cucumber me use hota hai.
Hinglish: Given, When, Then BDD format hai jo Cucumber me use hota hai.
- Given: Precondition
- When: Action
- Then: Expected result
31. How do you pass test data from Excel to a method?
English: We pass test data from Excel using Apache
POI and DataProvider in TestNG.
Hinglish: Hum Apache POI aur DataProvider ka use karke Excel se data method me pass karte hain.
Hinglish: Hum Apache POI aur DataProvider ka use karke Excel se data method me pass karte hain.
@DataProvider(name="excelData")
public Object[][] getData() {
return new Object[][] {
{"admin","1234"},
{"user","5678"}
};
}
@Test(dataProvider="excelData")
public void loginTest(String user, String pass) {
System.out.println(user + " " + pass);
}
32. Explain BDD (Behavior Driven Development).
English: BDD is a testing approach where test cases are
written in simple English language using Given, When, Then format. It improves
communication.
Hinglish: BDD ek testing approach hai jisme test cases simple English me likhe jaate hain taaki communication better ho.
Hinglish: BDD ek testing approach hai jisme test cases simple English me likhe jaate hain taaki communication better ho.
33. How do you automate login with username and password?
English: We locate fields and pass values using
Hinglish: Hum locator find karke
sendKeys, then click login.Hinglish: Hum locator find karke
sendKeys se data enter karte hain aur click perform karte hain.driver.findElement(By.id("username")).sendKeys("admin");
driver.findElement(By.id("password")).sendKeys("12345");
driver.findElement(By.id("loginBtn")).click();
34. How do you connect and validate database scenarios in your framework?
English: We use JDBC to connect with the
database. After executing SQL queries, we validate the data with UI results.
Hinglish: Hum JDBC se DB connect karte hain aur SQL query se data fetch karke UI se compare karte hain.
Hinglish: Hum JDBC se DB connect karte hain aur SQL query se data fetch karke UI se compare karte hain.
35. How do you pass files in your framework? (File Upload)
English: We use
Hinglish: Hum
sendKeys method to upload files
by passing the absolute file path.Hinglish: Hum
sendKeys me file ka path
pass karte hain upload ke liye.driver.findElement(By.id("upload")).sendKeys("C:\\testdata\\file.txt");
36. Explain your TestNG framework.
English: Based on TestNG and follows Page Object Model. It
contains Base, Page, Test, and Utility classes. Maven is used for dependency management.
Hinglish: Mera framework TestNG aur POM par based hai. Isme Maven, Base, Page, aur Test classes ka use hota hai.
Hinglish: Mera framework TestNG aur POM par based hai. Isme Maven, Base, Page, aur Test classes ka use hota hai.
37. What is the Difference Between Cucumber and TestNG? (Deep Dive)
1. What is Cucumber?
English: BDD tool that uses Gherkin (Given/When/Then). Best for collaboration.
Hinglish: Isme scenarios English me likhte hain.
2. What is TestNG?
English: Testing framework for Java for execution and reporting.
English: BDD tool that uses Gherkin (Given/When/Then). Best for collaboration.
Hinglish: Isme scenarios English me likhte hain.
2. What is TestNG?
English: Testing framework for Java for execution and reporting.
@Test
public void loginTest() {
System.out.println("Login Test Executed");
}
3. Comparison Points:| Feature | Cucumber | TestNG |
|---|---|---|
| Purpose | Describe behavior | Execute test cases |
| Readability | Very Easy | Technical |
38. What is POM (Page Object Model)?
English: POM is a design pattern where each web page is
represented by a separate class with its locators and actions.
Hinglish: Har page ke liye alag class banana aur usme methods likhna POM เคเคนเคฒเคพเคคเคพ hai.
Hinglish: Har page ke liye alag class banana aur usme methods likhna POM เคเคนเคฒเคพเคคเคพ hai.
39. How do you perform parallel execution in Selenium?
English: Done using TestNG by setting
Hinglish: xml file me parallel options set karke hum execution speed badha sakte hain.
parallel
and thread-count in testng.xml.Hinglish: xml file me parallel options set karke hum execution speed badha sakte hain.
<suite name="Suite" parallel="tests" thread-count="2">
40. How do you handle a new window in Selenium?
English: Use
Hinglish: IDs fetch karke specific window ID par switch karte hain.
getWindowHandles() to get IDs and
switchTo().window(ID) to switch.Hinglish: IDs fetch karke specific window ID par switch karte hain.
41. How do you handle mouse hover in Selenium?
English: Handled using Actions class with
Hinglish: Actions class ka use karke cursor move karate hain.
moveToElement() method.Hinglish: Actions class ka use karke cursor move karate hain.
42. How do you handle Web Tables in Selenium?
English: We use XPath to access rows (
Hinglish: XPath se logic bante hain:
tr) and
columns (td).Hinglish: XPath se logic bante hain:
//table//tr[2]/td[3] code specific cell ke liye.
43. How do you handle keyboard operations in Selenium?
English: Handled using Actions class or
sendKeys().Actions act = new Actions(driver); act.sendKeys(Keys.ENTER).perform();
44. How do you handle double click in Selenium?
English: Use
doubleClick(element) method of
Actions class.Actions act = new Actions(driver); act.doubleClick(element).perform();
45. How do you clear browser cache in automation?
English: Deleting cookies is the common way.
Hinglish: Saare cookies delete karke cache effect handle karte hain.
driver.manage().deleteAllCookies();Hinglish: Saare cookies delete karke cache effect handle karte hain.
46. How do you find XPath of an element?
English: Use Browser DevTools (Inspect) and create
relative/dynamic XPath.
Hinglish: Element inspect karke relative path banate hain (e.g.,
Hinglish: Element inspect karke relative path banate hain (e.g.,
//input[@id='username']).
47. How do you create a Maven project for Selenium?
English: Create Maven project in IDE and add dependencies in
Sample pom.xml:
pom.xml.Sample pom.xml:
<dependencies>
<!-- Selenium -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.18.1</version>
</dependency>
</dependencies>
48. How do you write a test automation script?
English: Open browser โ Go to URL โ Locate Elements โ
Perform Actions โ Validate.
driver.get("https://example.com");
driver.findElement(By.id("user")).sendKeys("admin");
driver.findElement(By.id("login")).click();
49. What is TestNG?
English: TestNG is a testing framework used with Selenium
for better execution control and reporting.
Hinglish: Test cases manage aur execute karne ka modern framework.
Hinglish: Test cases manage aur execute karne ka modern framework.
50. What are different TestNG annotations?
@BeforeSuite, @BeforeTest, @BeforeClass,
@BeforeMethod, @Test, @AfterMethod,
@AfterClass, @AfterTest, @AfterSuite
51. What is TestNG Suite?
English: An XML file (
Hinglish: XML file jo batches of tests ko control karti hai.
testng.xml) used to
control test execution (parallel, group, listeners).Hinglish: XML file jo batches of tests ko control karti hai.
52. What are waits in Selenium?
English: Used to synchronize Selenium with web elements to
prevent errors like NoSuchElementException.
Hinglish: Page load hone aur elements appear hone ka wait karne ke liye dynamic mechanism.
Hinglish: Page load hone aur elements appear hone ka wait karne ke liye dynamic mechanism.
53. Difference between Implicit and Explicit Wait.
| Implicit Wait | Explicit Wait |
|---|---|
| Applies globally | Applies to specific element |
| Defined once | Defined for each condition |
| Less flexible | More flexible |
54. If priority is not given in TestNG, how are test cases executed?
English: TestNG executes test cases in alphabetical
order by default.
Hinglish: Default default alphabet order follow hota hai agar priority mention nahi hai.
Hinglish: Default default alphabet order follow hota hai agar priority mention nahi hai.
55. Explain Hybrid Driven Framework.
English: Hybrid framework is the combination of Data Driven,
Keyword Driven, and POM framework.
Hinglish: Hybrid framework Data Driven, Keyword Driven aur POM ka combination hota hai.
Hinglish: Hybrid framework Data Driven, Keyword Driven aur POM ka combination hota hai.
56. How do you find XPath of an element?
English: Steps:
1. Right click on element → Click Inspect
2. Check attributes like id, name, class
3. Create XPath:
Hinglish: Element par right click karke inspect karo aur attributes (id/name) ke base par XPath banao.
1. Right click on element → Click Inspect
2. Check attributes like id, name, class
3. Create XPath:
//input[@id='username']Hinglish: Element par right click karke inspect karo aur attributes (id/name) ke base par XPath banao.
57. How do you extract all links from a webpage?
English: We use
findElements with the tag name
"a" and iterate to get "href" attributes.List<WebElement> links = driver.findElements(By.tagName("a"));
for(WebElement link : links){
System.out.println(link.getAttribute("href"));
}
Hinglish: "a" tag se findElements
karke loop chalate hain aur attribute fetch karte hain.
58. XPath for "Navigate your next" (Infosys example)
//a[text()='Navigate your next']Hinglish: Hum exact text match ke liye
text() function use karte hain.
59. What is Dynamic XPath?
English: Dynamic XPath is used when attribute values change
on every reload (e.g., dynamic IDs).
Example:
Hinglish: Jab ID prefix constant ho par numbers badalte rahein tab
Example:
//input[contains(@id,'user')]Hinglish: Jab ID prefix constant ho par numbers badalte rahein tab
contains() use karte hain.
60. On which project have you worked?
English: I worked on a web automation project using
Selenium, Java, and TestNG for an E-commerce/Banking application.
Hinglish: Maine Selenium aur TestNG framework ka use karke real-time automation project par kaam kiya hai.
Hinglish: Maine Selenium aur TestNG framework ka use karke real-time automation project par kaam kiya hai.
61. How to find XPath on any e-commerce site? (Search Box)
English: Inspect the search input field and use its type or
placeholder.
Example:
Example:
//input[@type='search'] or
//input[@placeholder='Search']
62. Difference between Absolute and Relative XPath.
English:
- Absolute: Full path from root (starts with /). Unstable.
- Relative: Short path (starts with //). Stable and reliable.
Hinglish: Absolute root node se start hota hai, relative attributes se beech me se start hota hai.
- Absolute: Full path from root (starts with /). Unstable.
- Relative: Short path (starts with //). Stable and reliable.
Hinglish: Absolute root node se start hota hai, relative attributes se beech me se start hota hai.
63. Which framework is used in your current automation?
English: I use a Hybrid Framework which combines Page Object
Model (POM), Data Driven (using Excel), and TestNG.
Hinglish: Main Hybrid framework (POM + Data Driven + TestNG) use karta hoon.
Hinglish: Main Hybrid framework (POM + Data Driven + TestNG) use karta hoon.
64. Do you use TestNG? Why?
English: Yes, for test execution, prioritizing tests,
grouping, and generating HTML reports.
Hinglish: Haan, execution control aur automatic reports ke liye TestNG perfect hai.
Hinglish: Haan, execution control aur automatic reports ke liye TestNG perfect hai.
65. What is Stale Element Reference Exception?
English: It occurs when an element is no longer present in
the DOM, usually after a page refresh.
Hinglish: Jab element reference purana ho jaye (refresh ke baad), tab ye exception aata hai.
Hinglish: Jab element reference purana ho jaye (refresh ke baad), tab ye exception aata hai.
66. Common Locators in Selenium.
ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, XPath, and CSS Selector.
Hinglish: Sabse common ID, Name aur XPath use hote hain.
Hinglish: Sabse common ID, Name aur XPath use hote hain.
67. How to find XPath efficiently?
English: Always prefer ID or Name. If not available, use
unique attributes with Relative XPath.
Hinglish: Element inspect karke unique id ya text se dynamic path nikalna sabse efficient hai.
Hinglish: Element inspect karke unique id ya text se dynamic path nikalna sabse efficient hai.
68. How to handle mouse operations?
English: We use the Actions class for mouse
hover, right click, and double click.
Actions act = new Actions(driver); act.moveToElement(element).click().perform();
69. How to handle dropdowns using Selenium?
English: We use the Select class for
<select> tags.
Select s = new Select(element);
s.selectByVisibleText("India");
70. How to select the first value in a dropdown?
s.selectByIndex(0);Hinglish: Index series 0 se start hoti hai, isliye zero index first value select karta hai.
71. Which locators do you commonly use?
English: I commonly use ID and Relative XPath because they
are very stable.
Hinglish: Main jyadatar ID aur XPath use karta hoon kyunki ye reliable hain.
Hinglish: Main jyadatar ID aur XPath use karta hoon kyunki ye reliable hain.
72. Why use relative XPath over absolute XPath?
English: Relative XPath is much more stable and does not
break if the UI layout changes slightly.
Hinglish: Relative small hota hai aur tab bhi kaam karta hai jab HTML structure me minor changes ho jayein.
Hinglish: Relative small hota hai aur tab bhi kaam karta hai jab HTML structure me minor changes ho jayein.
73. How to handle JavaScript alerts?
Alert a = driver.switchTo().alert(); a.accept(); // Click OK a.dismiss(); // Click CancelHinglish: Alert interface se hum popup buttons handle karte hain.
74. Difference between Implicit and Explicit wait with code.
// Implicit (Global) driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // Explicit (Specific) WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.visibilityOf(element));Hinglish: Implicit wait poore driver session ke liye hota hai, explicit visibility conditional hota hai.
75. Where is the test data kept in a framework?
English: Test data is usually kept in external files like
Excel (.xlsx), JSON, or Properties files.
Hinglish: Hum data script me hardcode nahi karte, Excel ya config files me rakhte hain.
Hinglish: Hum data script me hardcode nahi karte, Excel ya config files me rakhte hain.
76. What are the common TestNG annotations?
@Test, @BeforeMethod, @AfterMethod,
@BeforeClass, @AfterClass, @BeforeSuite.Hinglish: Ye annotations hume execution workflow manage karne me help karte hain.
77. Why do we use @BeforeMethod?
English: To run setup code (like opening a browser or
logging in) before every
Hinglish: Har test case se pehle chalta hai, configuration tasks ke liye.
@Test case.Hinglish: Har test case se pehle chalta hai, configuration tasks ke liye.
78. Sample Selenium script: Login and Validate Product.
// Login Steps
driver.findElement(By.id("user")).sendKeys("admin");
driver.findElement(By.id("pass")).sendKeys("123");
driver.findElement(By.id("login")).click();
// Search Product
driver.findElement(By.id("search")).sendKeys("Laptop");
driver.findElement(By.id("btn")).click();
// Validation
String actual = driver.findElement(By.xpath("//h2")).getText();
if(actual.contains("Laptop")) {
System.out.println("Test Passed: Product found");
}
Hinglish: Login karke product search perform karte
hain aur product header se validation karte hain.
Top 20 Important Java Programs
1. How to Reverse a String in Java?
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String rev = "";
for(int i=str.length()-1; i>=0; i--){
rev = rev + str.charAt(i);
}
System.out.println(rev);
}
}
English: The loop starts from the last index and appends
characters in reverse order.Hinglish: Loop last character se start hota hai aur characters ko reverse order me add karta hai.
Output: olleh
2. How to check if a String is a Palindrome?
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String rev = "";
for(int i=str.length()-1;i>=0;i--){
rev = rev + str.charAt(i);
}
if(str.equals(rev))
System.out.println("Palindrome");
else
System.out.println("Not Palindrome");
}
}
English: A palindrome string reads the same forward and
backward (e.g., madam, level).Hinglish: Palindrome string aage aur piche se same hoti hai.
3. Swap Two Numbers without a third variable.
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;
a = a + b; // 15
b = a - b; // 5
a = a - b; // 10
System.out.println("a: " + a + ", b: " + b);
}
}
Hinglish: Addition aur subtraction logic use karke
numbers swap kiye gaye hain.
4. How to generate Fibonacci Series?
public class Fibonacci {
public static void main(String[] args) {
int a=0, b=1, c;
for(int i=1; i<=10; i++){
System.out.print(a + " ");
c = a + b;
a = b;
b = c;
}
}
}
English: Each number is the sum of previous two numbers.Example: 0 1 1 2 3 5 8
5. Find the Largest Number in an Array.
public class LargestNumber {
public static void main(String[] args) {
int arr[] = {10, 20, 5, 30, 15};
int max = arr[0];
for(int i=1; i<arr.length; i++){
if(arr[i] > max) max = arr[i];
}
System.out.println(max);
}
}
Hinglish: Har element ko variable 'max' se compare
karke largest number find karte hain.Output: 30
6. Count Vowels in a String.
public class CountVowels {
public static void main(String[] args) {
String s = "automation";
int count = 0;
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u') count++;
}
System.out.println(count);
}
}
Hinglish: A, E, I, O, U vowels ko check karke
counter increment karte hain.
7. Find Duplicate Characters in a String.
public class DuplicateChar {
public static void main(String[] args) {
String s = "programming";
for(int i=0; i<s.length(); i++){
for(int j=i+1; j<s.length(); j++){
if(s.charAt(i) == s.charAt(j)){
System.out.println(s.charAt(i));
}
}
}
}
}
Hinglish: Nested loops use karke har character ko
baaki characters se compare kiya jata hai.
8. How to Reverse an Array?
public class ReverseArray {
public static void main(String[] args) {
int arr[] = {1, 2, 3, 4, 5};
for(int i=arr.length-1; i>=0; i--){
System.out.print(arr[i] + " ");
}
}
}
English: Loop starts from the last index (`length-1`) to
print in reverse order.
9. Count Words in a String.
public class CountWords {
public static void main(String[] args) {
String s = "Java Selenium Automation";
String words[] = s.split(" ");
System.out.println(words.length);
}
}
Output: 3
10. Check if a number is Prime.
public class PrimeNumber {
public static void main(String[] args) {
int num = 7, count = 0;
for(int i=1; i<=num; i++){
if(num % i == 0) count++;
}
if(count == 2) System.out.println("Prime");
else System.out.println("Not Prime");
}
}
English: A prime number has exactly two factors: 1 and
itself.
11. Remove Spaces from a String.
String s = "Java Selenium";
s = s.replace(" ", "");
System.out.println(s);
Hinglish: replace() method string se
saare spaces remove kar deta hai.
12. Find String Length without using length() method.
String s = "automation";
int count = 0;
for(char c : s.toCharArray()) {
count++;
}
System.out.println(count);
13. Find the Second Largest Number in an Array.
public class SecondLargest {
public static void main(String[] args) {
int arr[] = {10, 20, 30, 40};
int largest=0, second=0;
for(int num : arr){
if(num > largest){
second = largest;
largest = num;
} else if (num > second && num != largest) {
second = num;
}
}
System.out.println(second);
}
}
14. Print even numbers from an Array.
int arr[] = {1, 2, 3, 4, 5, 6};
for(int i=0; i<arr.length; i++){
if(arr[i] % 2 == 0) System.out.println(arr[i]);
}
15. Sum of all elements in an Array.
int arr[] = {10, 20, 30};
int sum = 0;
for(int i=0; i<arr.length; i++){
sum = sum + arr[i];
}
System.out.println(sum);
16. Print odd numbers between 1 to 10.
for(int i=1; i<=10; i++){
if(i % 2 != 0) System.out.println(i);
}
17. Reverse words in a sentence.
String s = "Java Selenium";
String words[] = s.split(" ");
for(int i=words.length-1; i>=0; i--){
System.out.print(words[i] + " ");
}
18. Find duplicates in an Array.
int arr[] = {1, 2, 2, 3, 4, 4};
for(int i=0; i<arr.length; i++){
for(int j=i+1; j<arr.length; j++){
if(arr[i] == arr[j]) System.out.println(arr[i]);
}
}
19. Check if two Strings are Anagrams.
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String s1="listen", s2="silent";
char a[]=s1.toCharArray(), b[]=s2.toCharArray();
Arrays.sort(a); Arrays.sort(b);
if(Arrays.equals(a,b)) System.out.println("Anagram");
}
}
20. Print All Possible Pairs from a String.
String s = "abcd";
for(int i=0; i<s.length(); i++){
for(int j=i+1; j<s.length(); j++){
System.out.println(s.charAt(i) + "" + s.charAt(j));
}
}
Output: ab, ac, ad, bc, bd, cd
21. How to generate a Random Alphanumeric String in Java?
import java.util.Random;
public class RandomStringExample {
public static void main(String[] args) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 10; i++) {
sb.append(chars.charAt(random.nextInt(chars.length())));
}
System.out.println(sb.toString());
}
}
22. Check if a number is Odd or Even without using the '%' operator.
English: Divide the number by 2, multiply by 2, and compare
with original number. Or use Bitwise AND.
// Bitwise Method (Fastest)
if ((num & 1) == 1) System.out.println("Odd");
else System.out.println("Even");
Hinglish: (num & 1) == 1 logic se bit
level par checking hoti hai.
Advanced Automation & SDLC
23. What is Time Complexity and why is it important?
English: Time Complexity measures how much time an algorithm
takes relative to input size. Common notations: O(1), O(n), O(nยฒ).
Hinglish: Ye batata hai ki input badhne par code kitna slow ya fast chalega. O(n) loop ke liye hota hai.
Hinglish: Ye batata hai ki input badhne par code kitna slow ya fast chalega. O(n) loop ke liye hota hai.
24. What is a Keyword Driven Framework?
English: A framework where actions (Click, Enter, etc.) are
stored as keywords in external files (Excel/CSV). Script reads keywords and executes
accordingly.
Hinglish: Isme Excel me "ClickLogin" jese keywords likhte hain aur code un keywords ko actions me convert karta hai.
Hinglish: Isme Excel me "ClickLogin" jese keywords likhte hain aur code un keywords ko actions me convert karta hai.
25. Explain Selenium Grid and its Hub-Node architecture.
English: Tool for parallel execution on multiple
machines/browsers. Hub is the central server; Nodes are
the actual execution machines.
Hinglish: Hub driver se command leta hai aur available Node par test bhej deta hai cross-browser testing ke liye.
Hinglish: Hub driver se command leta hai aur available Node par test bhej deta hai cross-browser testing ke liye.
26. Behavioral Question: Why should we hire you?
English: "I have 10 years in QA, with strong expertise in
Selenium/Java frameworks. I've led teams and delivered high-quality releases
consistently."
Hinglish: Apne years of experience, framework building knowledge aur problem-solving skills ko highlight karein.
Hinglish: Apne years of experience, framework building knowledge aur problem-solving skills ko highlight karein.
27. How do you raise a defect in Jira? (Standard Steps)
English: Login → Create Issue → Type: Bug →
Fill Summary, Description, Steps to Reproduce, Expected/Actual results → Attach
Screenshots.
Hinglish: Steps to reproduce sabse important part hai taaki developer issue recreate kar sake.
Hinglish: Steps to reproduce sabse important part hai taaki developer issue recreate kar sake.
28. Explain the Agile Process (Scrum, Sprints, Ceremonies).
English: Iterative methodology dividing project into 2-4
week Sprints. Ceremonies: Sprint Planning, Daily Stand-up, Review, and
Retrospective.
Hinglish: Agile me client feedback jaldi milta hai aur changes handle karna easy hota hai.
Hinglish: Agile me client feedback jaldi milta hai aur changes handle karna easy hota hai.
29. Interview Tip: Which framework are you using?
English: "We use a Hybrid Framework,
combining Data-Driven (Excel), Keyword-Driven (for maintenance), and Page Object Model with
Maven/TestNG."
Hinglish: Humesha 'Hybrid' bole kyunki real project me multiple patterns mix hote hain.
Hinglish: Humesha 'Hybrid' bole kyunki real project me multiple patterns mix hote hain.
Core Java Mastery (Expert Mode)
1. Explain OOPS Concepts and how they are used in Automation.
English:
- Encapsulation: Used in POM (Page Object Model) to wrap data and methods (Private variables, Public getters).
- Abstraction: Hiding implementation details, used in Base classes and utility interfaces.
- Inheritance: Reusability; test classes
- Polymorphism: Method overloading (same name, different parameters) and cross-browser testing (WebDriver interface).
Hinglish: Encapsulation = data hide karna. Inheritance = parents se child banana. Abstraction = sirf important details dikhana.
- Encapsulation: Used in POM (Page Object Model) to wrap data and methods (Private variables, Public getters).
- Abstraction: Hiding implementation details, used in Base classes and utility interfaces.
- Inheritance: Reusability; test classes
extends a
Base/Utility class.- Polymorphism: Method overloading (same name, different parameters) and cross-browser testing (WebDriver interface).
Hinglish: Encapsulation = data hide karna. Inheritance = parents se child banana. Abstraction = sirf important details dikhana.
2. Java Code to Read a Properties (Config) File.
import java.io.FileInputStream;
import java.util.Properties;
public class ReadConfig {
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("src/test/resources/config.properties");
prop.load(fis);
System.out.println("Browser: " + prop.getProperty("browser"));
System.out.println("URL: " + prop.getProperty("url"));
}
}
Hinglish: Properties class load()
function se file read karti hai aur getProperty() se values fetch.
3. How do you take a screenshot in Selenium? (Practical Code)
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
TakesScreenshot ts = (TakesScreenshot) driver;
File source = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("D:\\Screenshots\\error.png"));
English: Cast the driver to TakesScreenshot,
capture the file, and save it using FileUtils or FileHandler.
4. How to read data from an Excel sheet using Apache POI?
FileInputStream file = new FileInputStream("D:\\TestData.xlsx");
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheet("Sheet1");
String user = sheet.getRow(1).getCell(0).getStringCellValue();
String pass = sheet.getRow(1).getCell(1).getStringCellValue();
Hinglish: Excel structure (Workbook → Sheet
→ Row → Cell) follow karke data iterate karna padta hai.
5. Difference between Method Overloading and Overriding.
English:
- Overloading: Same name, different parameters, within same class (Compile-time).
- Overriding: Subclass provides specific implementation of parent method (Run-time).
Hinglish: Overloading "static binding" hai, Overriding "dynamic binding" jo inheritance ki vajah se possible hai.
- Overloading: Same name, different parameters, within same class (Compile-time).
- Overriding: Subclass provides specific implementation of parent method (Run-time).
Hinglish: Overloading "static binding" hai, Overriding "dynamic binding" jo inheritance ki vajah se possible hai.
6. Difference between ArrayList and LinkedList with use cases.
English: ArrayList uses dynamic arrays,
best for random access/retrieval. LinkedList uses nodes, best for frequent
add/remove operations.
Hinglish: Search karne ke liye ArrayList fast hai, element delete/add karne ke liye LinkedList.
Hinglish: Search karne ke liye ArrayList fast hai, element delete/add karne ke liye LinkedList.
7. Why is String immutable in Java?
English: For security, memory optimization (String Pool
caching), and thread safety. Once created, its value cannot be altered in memory.
Hinglish: Memory save karne ke liye String Pool use hota hai jisme duplicate values create nahi hoti, isliye isse immutable rakha gaya hai.
Hinglish: Memory save karne ke liye String Pool use hota hai jisme duplicate values create nahi hoti, isliye isse immutable rakha gaya hai.
8. Java Program to Check if a number is Prime.
int num = 17; boolean isPrime = true;
if (num <= 1) isPrime = false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) { isPrime = false; break; }
}
System.out.println(isPrime ? "Prime" : "Not Prime");
9. Write a program to print duplicate elements in an array.
int[] arr = {1, 2, 3, 2, 4, 3, 5, 1};
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] == arr[j]) System.out.println("Duplicate: " + arr[i]);
}
}
10. Java program to reverse a given string without using inbuilt functions.
String input = "Selenium", reverse = "";
for(int i = input.length() - 1; i >= 0; i--) {
reverse = reverse + input.charAt(i);
}
System.out.println("Reversed: " + reverse);
11. Define a class and show how it's called using an object.
class Car { void start(){ System.out.println("Car started"); } }
public class Test {
public static void main(String[] args){
Car myCar = new Car(); // Object creation
myCar.start(); // Calling method
}
}
Hinglish: Class ek design hai, bina object banaye
hum uske state data ya behavior ko access nahi kar sakte.
12. Explain and show a Try-Catch block example in Java.
try {
int data = 100 / 0; // Risky code
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("Cleanup activities here");
}
13. Java program to sort an array and remove duplicates.
int[] arr = {5, 2, 8, 2, 5, 1};
Arrays.sort(arr);
int n = arr.length; int[] temp = new int[n]; int j = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] != arr[i+1]) temp[j++] = arr[i];
}
temp[j++] = arr[n-1];
for (int i=0; i<j; i++) System.out.print(temp[i] + " ");
14. What are Getter and Setter methods and why are they used?
English: They are used for Data
Encapsulation. Private variables can only be accessed through these public
methods, ensuring data validation and security.
Hinglish: User ko direct variable control nahi dete, getters/setters validation layer ki tarah kaam karte hain.
Hinglish: User ko direct variable control nahi dete, getters/setters validation layer ki tarah kaam karte hain.
15. What is an Interface in Java? (Blueprint Theory)
English: An interface defines "what" a class should do,
without specifying "how". All methods are abstract by default (before Java 8).
Hinglish: Interface classes ko ek particular set of rules follow karne ke liye majboor karta hai.
Hinglish: Interface classes ko ek particular set of rules follow karne ke liye majboor karta hai.
16. What is StringBuilder and how it is different from String?
English: StringBuilder is mutable (can be changed). String
creates a new object in memory for every concatenation, but StringBuilder modifies the same
object, making it much faster for loops.
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Modifies same memory space
17. List the most commonly used String methods in automation.
length() - gets character countcharAt(index) - gets specific charequals() & equalsIgnoreCase() - string comparisoncontains() - substring checksplit() - breaking string based on regexsubstring(start, end) - extracting text
18. Difference between Array and List (ArrayList).
English: Arrays have a static size and store primitives.
ArrayList has a dynamic size (auto-resizable) and provides rich API methods like
Hinglish: Array me size pehle batana padta hai, ArrayList me data ke hisab se size apne aap badhta hai.
add(), remove(), etc.Hinglish: Array me size pehle batana padta hai, ArrayList me data ke hisab se size apne aap badhta hai.
19. Difference between Map and Dictionary (Legacy vs Modern).
English: Map (interface) allows null keys/values in HashMap.
Dictionary is a legacy class (now obsolete) that was fully synchronized and didn't allow
nulls.
Hinglish: Aaj ke time me HashMap (Map interface) standard hai speed aur flexibility ki wajah se.
Hinglish: Aaj ke time me HashMap (Map interface) standard hai speed aur flexibility ki wajah se.
20. How to iterate over List, Map, and Set structures?
// List/Set iteration
for(String val : set) { System.out.println(val); }
// Map iteration (Modern way)
map.forEach((k, v) -> System.out.println("Key: " + k + ", Value: " + v));
Hinglish: Enhanced for-loop list/set ke liye best
hai; Map ke liye entrySet() ya lambda use karte hain.
21. What is a variable and explain its types (Static vs Instant).
English: Variables are data containers.
Static belongs to the class (memory shared); Instance
belongs to an object; Local exists only within a method.
Hinglish: Static pure class ke objects ke liye common hota hai, instance objects ke hisab se alag hota hai.
Hinglish: Static pure class ke objects ke liye common hota hai, instance objects ke hisab se alag hota hai.
22. What is a Wrapper Class and its use in Collections?
English: Since Collections store objects, we need Wrapper
classes to treat primitives as objects (e.g.,
Hinglish: Primitive values (int, char) ko ArrayList me store karne ke liye Integer/Character objects me convert karna padta hai.
Integer for
int).Hinglish: Primitive values (int, char) ko ArrayList me store karne ke liye Integer/Character objects me convert karna padta hai.
23. How are Java Collections used in real Test Automation?
English: Used for storing multiple WebElements (using
Hinglish: Browser windows handle karne ke liye
findElements), management of Window Handles (Sets), and mapping environment
variables (Maps).Hinglish: Browser windows handle karne ke liye
Set<String> use hota hai aur elements list ke liye
List<WebElement>.
24. Java program for Array of String iteration.
String[] fruits = {"Apple", "Banana", "Orange"};
for(int i=0; i<fruits.length; i++){
System.out.println("Index " + i + ": " + fruits[i]);
}
25. Logic to find duplicate characters in a given String.
String str = "testing"; char[] chars = str.toCharArray();
for(int i=0; i<str.length(); i++){
for(int j=i+1; j<str.length(); j++){
if(chars[i] == chars[j]) System.out.println("Duplicate: " + chars[i]);
}
}
26. Find the length of a String without using the internal library length().
String s = "Automation"; int length = 0;
for(char c : s.toCharArray()) length++;
System.out.println("Computed Length: " + length);
27. Briefly explain Collection, Map, and List hierarchy.
Collection Interface: Parent of List, Set, Queue.
List: Ordered, allows duplicates.
Map: Independent interface, stores Key-Value pairs (no duplicates in keys).
List: Ordered, allows duplicates.
Map: Independent interface, stores Key-Value pairs (no duplicates in keys).
28. Program to reverse a String based on user input (Scanner).
Scanner sc = new Scanner(System.in);
System.out.println("Enter string:");
String s = sc.nextLine(); String rev = "";
for(int i=s.length()-1; i>=0; i--) rev += s.charAt(i);
System.out.println("User Reverse: " + rev);
29. Program for sorting a String Array alphabetically.
String arr[] = {"Zebra", "Apple", "Monkey"};
Arrays.sort(arr); // Apple, Monkey, Zebra
Hinglish: Arrays.sort() utility
function comparison algorithm use karke strings ko order me set karta hai.
30. Difference between Abstraction (Class) and Interface.
English: Abstract classes can have state (variables) and
partial implementation (non-abstract methods). Interfaces only define method signatures
(strictly abstract before Java 8).
Hinglish: Agar base design common rakhna ho toh abstract class; agar sirf functionalities force karni hon toh interfaces.
Hinglish: Agar base design common rakhna ho toh abstract class; agar sirf functionalities force karni hon toh interfaces.
31. Program to find the second largest number in an unsorted array.
int nums[] = {5, 20, 10, 8, 25};
Arrays.sort(nums);
System.out.println("Second Largest: " + nums[nums.length-2]);
32. How to handle logic exceptions vs runtime environment failures?
English: Logic errors are fixed during coding. Environment
failures (like element timeout) are handled at runtime using
try-catch and
Selenium's WebDriverWait.
33. What is the 'final' keyword and its impact on class/method/variable?
English: final variable: value cannot
change; final method: cannot be overridden; final class:
prevents inheritance.
Hinglish: Final se security multi hai taaki koi aapki class ka behavior change (override) na kar sake.
Hinglish: Final se security multi hai taaki koi aapki class ka behavior change (override) na kar sake.
34. What is the purpose of the 'this' keyword in Java constructors?
English: It prevents naming conflict between local variables
and instance variables by specifically referencing the current object instance.
public class MyClass {
int x;
MyClass(int x) { this.x = x; } // 'this.x' belongs to object
}
35. Detailed explanation of all Inheritance types in Java.
1. Single: One level (Child → Parent).
2. Multilevel: Child → Parent → G-Parent.
3. Hierarchical: Multiple children of same parent.
4. Multiple: Only via Interfaces (preventing Diamond Problem).
5. Hybrid: Mix of above, using Interfaces in Java.
Hinglish: Java me ambiguity se bachne ke liye classes ke sath multiples inheritance block ki gayi hai.
2. Multilevel: Child → Parent → G-Parent.
3. Hierarchical: Multiple children of same parent.
4. Multiple: Only via Interfaces (preventing Diamond Problem).
5. Hybrid: Mix of above, using Interfaces in Java.
Hinglish: Java me ambiguity se bachne ke liye classes ke sath multiples inheritance block ki gayi hai.
๐ Cucumber Framework โ Question&Answer
1. Explain the framework structure which you are using in your Cucumber project.
English: In my Cucumber framework, we follow a modular structure:
- Feature files → contain test scenarios
- Step Definition classes → contain implementation of steps
- Runner class → executes feature files
- Page classes (POM) → contain locators and actions
- Utility classes → for common methods (wait, screenshot, excel)
- Hooks class → for setup and teardown
This structure improves reusability and maintainability.
Hinglish: Mere Cucumber framework me:
- Feature file → scenarios hote hain
- Step Definition → steps ka code hota hai
- Runner class → execution ke liye hoti hai
- Page classes (POM) → locators aur methods ke liye
- Utility classes → common methods ke liye
- Hooks class → browser setup aur close ke liye
Isse code reusable aur easy to maintain hota hai.
- Feature files → contain test scenarios
- Step Definition classes → contain implementation of steps
- Runner class → executes feature files
- Page classes (POM) → contain locators and actions
- Utility classes → for common methods (wait, screenshot, excel)
- Hooks class → for setup and teardown
This structure improves reusability and maintainability.
Hinglish: Mere Cucumber framework me:
- Feature file → scenarios hote hain
- Step Definition → steps ka code hota hai
- Runner class → execution ke liye hoti hai
- Page classes (POM) → locators aur methods ke liye
- Utility classes → common methods ke liye
- Hooks class → browser setup aur close ke liye
Isse code reusable aur easy to maintain hota hai.
2. What is a Feature file? What is inside it and explain each keyword.
English: A Feature file contains test scenarios written in Gherkin language.
Hinglish: Feature file me test scenarios likhe jaate hain Gherkin language me.
Keywords:
- Feature → describes application feature / functionality ka naam
- Scenario → test case
- Given → precondition
- When → action
- Then → expected result
- And / But → additional steps / extra steps
Hinglish: Feature file me test scenarios likhe jaate hain Gherkin language me.
Keywords:
- Feature → describes application feature / functionality ka naam
- Scenario → test case
- Given → precondition
- When → action
- Then → expected result
- And / But → additional steps / extra steps
3. Which annotations are used in the Test Runner class?
English: We use
Hinglish: Runner class me
@RunWith(Cucumber.class) and @CucumberOptions.Hinglish: Runner class me
@RunWith(Cucumber.class) aur @CucumberOptions use karte hain.
4. What attributes are used inside @CucumberOptions?
English / Hinglish: Common attributes used:
- features → path of feature file
- glue → step definition package / path
- plugin → report generate karta hai / reporting
- monochrome → console output readable
- dryRun → checks mapping of steps
- tags → run specific/selected scenarios
- features → path of feature file
- glue → step definition package / path
- plugin → report generate karta hai / reporting
- monochrome → console output readable
- dryRun → checks mapping of steps
- tags → run specific/selected scenarios
5. Write feature file for login credentials.
English: A feature file is written in Gherkin language for Cucumber.
Given = precondition
When = action
Then = result
Feature: Login Functionality Scenario: Valid Login Given user is on login page When user enters username and password And user clicks on login button Then user should be logged in successfullyHinglish: Feature file me hum plain English me steps likhte hain:
Given = precondition
When = action
Then = result
6. What are Tags in Cucumber and why do we use them?
English: Tags (e.g.,
Hinglish: Tags scenarios ko group karne ke kaam aate hain. Specific tests (jaise
@smoke, @regression) are used to group and organize test scenarios. They allow us to selectively run a specific set of tests without executing the entire suite.Hinglish: Tags scenarios ko group karne ke kaam aate hain. Specific tests (jaise
@smoke ya @regression) run karne ke liye hum in tags ka use karte hain.
7. Differences between Scenario and Scenario Outline?
English:
- Scenario: Runs a test case once with a single set of data.
- Scenario Outline: Runs the exact same test case multiple times using different datasets provided via an
Hinglish: Scenario tab use karte hain jab ek hi data set ho, aur Scenario Outline tab use hota hai jab same steps ko alag-alag data (Examples table) ke sath repeat karna ho.
- Scenario: Runs a test case once with a single set of data.
- Scenario Outline: Runs the exact same test case multiple times using different datasets provided via an
Examples table.Hinglish: Scenario tab use karte hain jab ek hi data set ho, aur Scenario Outline tab use hota hai jab same steps ko alag-alag data (Examples table) ke sath repeat karna ho.
8. What is the use of the 'Background' keyword in Cucumber?
English: The
Hinglish:
Background keyword groups steps that are common to all scenarios in a feature file (like logging into the application). These steps run automatically before each scenario.Hinglish:
Background common steps (jaise login) ko ek jagah rakhne ka tareeka hai, jo har scenario se pehle automatically execute hoti hain.
9. What is a Data Table in Cucumber?
English: A Data Table allows passing a list or grid of data directly inside a feature file step. It is commonly retrieved in the Step Definition as a
Hinglish: Feature file ke ek hi step me multiple data inputs pass karne ke liye Data Table banate hain, jise Java code me
List<List<String>> or a List<Map<String, String>>.Hinglish: Feature file ke ek hi step me multiple data inputs pass karne ke liye Data Table banate hain, jise Java code me
List ya Map ki tarah read kiya jata hai.
10. Explain Cucumber Hooks (@Before and @After).
English: Hooks are blocks of code that run seamlessly before or after scenarios.
- @Before: Executes before the first step of each scenario (e.g., initializing WebDriver).
- @After: Executes after the last step of each scenario (e.g., capturing a screenshot on failure or quitting the browser).
Hinglish: Hooks code blocks hain jo test ke aage-peeche chalte hain.
- @Before: Executes before the first step of each scenario (e.g., initializing WebDriver).
- @After: Executes after the last step of each scenario (e.g., capturing a screenshot on failure or quitting the browser).
Hinglish: Hooks code blocks hain jo test ke aage-peeche chalte hain.
@Before browser setup karne ke liye aur @After test end hone par driver close ya error screenshot lene ke liye use hota hai.
11. What is the purpose of 'dryRun' in @CucumberOptions?
English: Setting
Hinglish:
dryRun = true rapidly validates if every step in the Feature file has an associated Step Definition, without actually executing the underlying automation code. It is used to quickly spot missing steps.Hinglish:
dryRun = true check karta hai ki saare naye steps ka code likha hua hai ya nahi bina actual browser me test ko run kiye.
Framework Deep-Dive
Can you explain your TestNG automation framework structure?
English:
Yes, I have designed a TestNG-based automation framework using Selenium by following the Page Object Model (POM) design pattern.
The framework is modular and divided into multiple layers for better maintainability, reusability, and scalability. Below is the framework structure:
Project Structure:
Layer Explanations:
Overall, the framework is scalable, reusable, supports data-driven testing, reporting, retry mechanisms, and can be integrated with CI/CD tools like Jenkins.
Yes, I have designed a TestNG-based automation framework using Selenium by following the Page Object Model (POM) design pattern.
The framework is modular and divided into multiple layers for better maintainability, reusability, and scalability. Below is the framework structure:
Project Structure:
project-root/ โโโ src/test/java/ โ โโโ base/ โ โ โโโ BaseClass.java โ โโโ pages/ โ โ โโโ LoginPage.java โ โ โโโ Users_Management_Page.java โ โ โโโ Policies_Page.java โ โโโ testCases/ โ โ โโโ TC01_LoginTest.java โ โ โโโ TC19_Users_Management_Page.java โ โ โโโ TC05_Policies_Page.java โ โโโ utilities/ โ โ โโโ ConfigReader.java โ โ โโโ WaitUtils.java โ โ โโโ ScreenshotUtil.java โ โ โโโ ExcelUtil.java / ODSReader.java โ โ โโโ RetryAnalyzer.java โ โโโ listeners/ โ โ โโโ CustomReporter.java โโโ src/test/resources/ โ โโโ config/ โ โ โโโ config.properties โ โโโ testData/ โ โ โโโ testdata.xlsx / testdata.ods โโโ reports/ โโโ screenshots/ โโโ testng.xml โโโ pom.xml
Layer Explanations:
- 1. Base Layer: Contains BaseClass which handles WebDriver initialization, browser setup, and teardown methods.
- 2. Page Layer (POM): Contains all Page Object classes where web elements and reusable methods are defined. This ensures separation of UI logic from test logic.
- 3. Test Layer: Contains all TestNG test classes where test scenarios are written using annotations like @Test, @BeforeMethod, and @AfterMethod. Assertions are also implemented here.
- 4. Utilities: Includes reusable components like ConfigReader for reading properties, WaitUtils for synchronization, Screenshot utility for capturing failures, and Excel/ODS utilities for data-driven testing.
- 5. Listeners: Implements TestNG listeners to generate reports such as Extent Reports and to track test execution status.
- 6. Configuration File: config.properties is used to store environment-related data like URL, browser type, username, and password to avoid hardcoding.
- 7. Test Data: External data is maintained in Excel or ODS files for data-driven testing.
- 8. TestNG XML: testng.xml is used to manage test execution, grouping (smoke/regression), and parallel execution.
Overall, the framework is scalable, reusable, supports data-driven testing, reporting, retry mechanisms, and can be integrated with CI/CD tools like Jenkins.
๐ฏ Short Answer (Quick เคฌเฅเคฒเคจเฅ เคเฅ เคฒเคฟเค):
"I am using a TestNG-based automation framework with Selenium, following the Page Object Model. It includes layers like Base, Pages, Test Cases, Utilities, and Listeners. The framework supports data-driven testing, reporting, retry mechanism, and parallel execution using testng.xml."
"I am using a TestNG-based automation framework with Selenium, following the Page Object Model. It includes layers like Base, Pages, Test Cases, Utilities, and Listeners. The framework supports data-driven testing, reporting, retry mechanism, and parallel execution using testng.xml."
Can you explain your Cucumber automation framework structure?
English:
Yes, I have designed a hybrid automation framework using Selenium, Cucumber, and TestNG by following the Page Object Model (POM) design pattern.
The framework is divided into multiple layers to ensure better maintainability, reusability, and scalability. Below is the framework structure:
Project Structure:
Layer Explanations:
Overall, the framework supports data-driven testing, reporting, reusable components, and can be integrated with CI/CD tools like Jenkins.
Yes, I have designed a hybrid automation framework using Selenium, Cucumber, and TestNG by following the Page Object Model (POM) design pattern.
The framework is divided into multiple layers to ensure better maintainability, reusability, and scalability. Below is the framework structure:
Project Structure:
project-root/ โโโ src/test/java/ โ โโโ base/ โ โ โโโ BaseClass.java โ โโโ pages/ โ โ โโโ LoginPage.java โ โ โโโ Users_Management_Page.java โ โ โโโ Policies_Page.java โ โโโ stepdefinitions/ โ โ โโโ LoginSteps.java โ โโโ utilities/ โ โ โโโ ConfigReader.java โ โ โโโ WaitUtils.java โ โ โโโ ScreenshotUtil.java โ โ โโโ ExcelUtil.java โ โโโ runners/ โ โ โโโ TestRunner.java โ โโโ listeners/ โ โโโ CustomReporter.java โโโ src/test/resources/ โ โโโ features/ โ โ โโโ login.feature โ โโโ config/ โ โโโ config.properties โโโ reports/ โโโ screenshots/ โโโ testng.xml โโโ pom.xml
Layer Explanations:
- 1. Base Layer: Contains BaseClass which handles WebDriver initialization, browser setup, and teardown.
- 2. Page Layer (POM): Contains all Page Object classes where web elements and actions are defined. This helps in separating UI logic from test logic.
- 3. Step Definition Layer: Maps feature file steps (Given, When, Then) to Java methods. This acts as a bridge between feature files and automation code.
- 4. Feature Files: Written in Gherkin language and contain test scenarios in a readable format for both technical and non-technical users.
- 5. Runner Class: Uses TestNG with CucumberOptions to control test execution, specify feature file paths, glue code, and reporting.
- 6. Utilities: Reusable components like ConfigReader, WaitUtils, Screenshot utility, and Excel utility for data-driven testing.
- 7. Listeners: Used for generating reports like Extent Reports and capturing execution logs.
- 8. Config File: config.properties is used to store environment details such as URL, browser, username, and password.
- 9. TestNG XML: Used for grouping tests, parallel execution, and managing test suites.
Overall, the framework supports data-driven testing, reporting, reusable components, and can be integrated with CI/CD tools like Jenkins.
CI/CD Pipelines & DevOps for Automation
1. What is CI/CD, and how does it relate to test automation?
English: Continuous Integration (CI) is the practice of merging code and running automated tests on every commit. Continuous Deployment (CD) is automatically deploying the build to production after successful tests. Automation is the backbone of CI/CD, ensuring that new changes don't break existing features.
Hinglish: CI matlab code upload karte hi automatic tests chalna. CD matlab tests pass hone par code ko release karna. Setup automated hota hai taaki bugs jaldi mil sakein.
Hinglish: CI matlab code upload karte hi automatic tests chalna. CD matlab tests pass hone par code ko release karna. Setup automated hota hai taaki bugs jaldi mil sakein.
2. How do you integrate Selenium tests with Jenkins?
English: Steps for integration:
1. Create a Freestyle Project or Pipeline in Jenkins.
2. Configure Source Code Management (SCM) to pull code from Git.
3. Add a build step:
4. Use Post-build Actions to archive TestNG reports or send email notifications.
Hinglish: Jenkins me build create karke Git se code link karte hain aur 'mvn test' command chala kar reports save karte hain.
1. Create a Freestyle Project or Pipeline in Jenkins.
2. Configure Source Code Management (SCM) to pull code from Git.
3. Add a build step:
mvn test (for Maven projects).4. Use Post-build Actions to archive TestNG reports or send email notifications.
Hinglish: Jenkins me build create karke Git se code link karte hain aur 'mvn test' command chala kar reports save karte hain.
3. Explain Jenkins Pipeline (Jenkinsfile) for automation.
English: A Jenkinsfile defines the entire build/test process as code (Pipeline-as-Code).
pipeline {
agent any
stages {
stage('Checkout') { steps { git 'url' } }
stage('Build') { steps { sh 'mvn compile' } }
stage('Test') { steps { sh 'mvn test' } }
stage('Reporting') { steps { allure report } }
}
}
4. What is Headless Mode and why use it in CI/CD?
English: Headless mode runs the browser without a visible UI. It is essential in CI/CD environments (like Linux servers) where there is no display monitor.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
Hinglish: Headless browser screen ke bina backend me chalta hai. Linux servers par UI nahi hota isliye wahan headless mode compulsory hota hai.
Cloud Grid & Parallel Execution
1. What is a Cloud Grid (BrowserStack/SauceLabs) and why use it?
English: A Cloud Grid is a vendor-managed service that provides access to thousands of real devices and OS/browser versions remotely. It avoids the cost of maintaining a local physical lab.
Hinglish: BrowserStack hume remote devices access karne deta hai. Hume khud saare browsers aur phones kharidne ki zarurat nahi padti.
Hinglish: BrowserStack hume remote devices access karne deta hai. Hume khud saare browsers aur phones kharidne ki zarurat nahi padti.
2. How do you connect your Selenium script to BrowserStack?
English: We use RemoteWebDriver and provide the BrowserStack Hub URL with our Access Key.
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability("browserName", "Chrome");
URL url = new URL("https://USERNAME:KEY@hub.browserstack.com/wd/hub");
WebDriver driver = new RemoteWebDriver(url, capabilities);
3. How to achieve Parallel Execution in TestNG?
English: By using the
parallel attribute in testng.xml at the suite, test, or methods level.<suite name="Suite" parallel="tests" thread-count="2"> <test name="ChromeTest"> ... </test> <test name="FirefoxTest"> ... </test> </suite>Hinglish:
testng.xml me parallel attribute set karke hum ek sath multiple browsers par tests chala sakte hain.
4. What is a Tunnel (Local Testing) in Cloud Grids?
English: A tunnel (like BrowserStack Local) creates a secure connection between the Cloud provider and your local/private server, allowing you to test staging/VPN websites on cloud devices.
Hinglish: Tunnel ke zariye hum cloud devices par apne office ke server (localhost) wali website ko test kar sakte hain.
Hinglish: Tunnel ke zariye hum cloud devices par apne office ke server (localhost) wali website ko test kar sakte hain.
Docker for Selenium Grid
1. What is Docker and why use it for Selenium Grid?
English: Docker is a containerization platform that packages your grid environment into portable containers. It ensures consistency (same environment for all testers), scalability (easily add more browser nodes), and isolation (tests don't interfere with each other).
Hinglish: Docker se hum browser aur hub ko containers mein pack kar sakte hain. Isse hume alag-alag computers pe setup nahi karna padta aur hum ek sath bahut saare browsers chala sakte hain.
Hinglish: Docker se hum browser aur hub ko containers mein pack kar sakte hain. Isse hume alag-alag computers pe setup nahi karna padta aur hum ek sath bahut saare browsers chala sakte hain.
2. How to run a Standalone Selenium Chrome container?
English: You can run a single container that contains both the Hub and the Chrome browser.
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:latestHinglish: Is command se ek browser container start ho jayega jise hum direct URL se connect kar sakte hain.
3. Explain 'docker-compose.yml' for Selenium Grid.
English: A YAML file used to define and run multi-container applications (Hub + Chrome Node + Firefox Node).
version: "3"
services:
selenium-hub:
image: selenium/hub:latest
ports: [ "4444:4444" ]
chrome:
image: selenium/node-chrome:latest
depends_on: [ selenium-hub ]
environment: [ SE_EVENT_BUS_HOST=selenium-hub ]
4. How to scale browser nodes using Docker Compose?
English: Use the
--scale flag to spin up multiple instances of a browser node instantly.docker-compose up --scale chrome=5 -dHinglish: Ek simple command se hum 5 chrome browsers ek sath khol sakte hain testing ke liye.
REST API Automation (RestAssured)
1. What is RestAssured and why use it for automation?
English: RestAssured is a Java library used for testing and validating REST services. Unlike Postman, it allows us to write BDD-style code (Given-When-Then), integrates with Maven/TestNG, and supports automated validation of response bodies using JSON tools.
Hinglish: RestAssured ek Java library hai APIs ko automate karne ke liye. Isse hum Java code likh kar API calls, responses aur assertions ko asani se handle kar sakte hain. Practice API Automation in Lab
Hinglish: RestAssured ek Java library hai APIs ko automate karne ke liye. Isse hum Java code likh kar API calls, responses aur assertions ko asani se handle kar sakte hain. Practice API Automation in Lab
2. Explain the Given, When, Then syntax in RestAssured.
English: RestAssured follows the BDD (Behavior Driven Development) structure:
- Given: Pre-requisites (Base URI, Headers, Query Params, Body).
- When: The action (GET, POST, PUT, DELETE with endpoint).
- Then: The verification (Status Code, Assertions, Response Body).
- Given: Pre-requisites (Base URI, Headers, Query Params, Body).
- When: The action (GET, POST, PUT, DELETE with endpoint).
- Then: The verification (Status Code, Assertions, Response Body).
given().header("Content-Type", "application/json")
.when().get("/users")
.then().statusCode(200);
3. How to extract a specific value from a JSON response?
English: We use the JsonPath class to navigate the JSON structure and extract fields.
Response res = given().get("/api/user");
JsonPath js = new JsonPath(res.asString());
String name = js.getString("data.first_name");
Hinglish: Response string ko JsonPath mein convert karke, 'key name' ke zariye hum kisi bhi value ko bahar nikal sakte hain.
4. What are Serialization and Deserialization in RestAssured?
English:
- Serialization: Converting a Java POJO (Plain Old Java Object) into a JSON/XML format to send as a request body.
- Deserialization: Converting a JSON/XML response back into a Java Object.
Hinglish: Java object ko JSON data banana (Sending) matlab Serialization. API ke JSON result ko waapas Java object bana dena matlab Deserialization.
- Serialization: Converting a Java POJO (Plain Old Java Object) into a JSON/XML format to send as a request body.
- Deserialization: Converting a JSON/XML response back into a Java Object.
Hinglish: Java object ko JSON data banana (Sending) matlab Serialization. API ke JSON result ko waapas Java object bana dena matlab Deserialization.
5. How to handle API authentication (Bearer Token)?
English: Authentication is usually passed in the Authorization header.
given().header("Authorization", "Bearer " + myToken)
.get("/secure-endpoint")
.then().statusCode(200);
6. What is the role of RequestSpecBuilder and ResponseSpecBuilder?
English: They are used to create reusable request and response components (e.g., Base URI, Content-Type) across multiple test cases, reducing code duplication.
Hinglish: Common details jaise Base URL aur Headers ko ek jagah rakhne ke liye builders ka use hota hai taaki code reusable ho sake.
Hinglish: Common details jaise Base URL aur Headers ko ek jagah rakhne ke liye builders ka use hota hai taaki code reusable ho sake.
Mobile Automation (Appium)
1. What is Appium and how does it work?
English: Appium is an open-source, cross-platform tool for automating native, hybrid, and mobile web apps. It uses the JSON Wire Protocol (now W3C) to communicate with the device. It has no dependency on the app's source code.
Hinglish: Appium mobile apps (Android aur iOS) automate karne ka tool hai. Ye humare Java code ko command ke roop mein server ko bhejta hai aur server usse mobile pe perform karta hai.
Hinglish: Appium mobile apps (Android aur iOS) automate karne ka tool hai. Ye humare Java code ko command ke roop mein server ko bhejta hai aur server usse mobile pe perform karta hai.
2. Explain Native, Hybrid, and Mobile Web apps.
English:
- Native: Built for a specific OS (Swift/Java). Fast and offline-friendly.
- Mobile Web: Websites accessed via a mobile browser.
- Hybrid: Web content inside a native wrapper (Cordova/React Native).
Hinglish: Native matlab jo sirf phone ke liye bani ho; Mobile Web matlab browser mein khulne wali site; Hybrid matlab donon ka mixture.
- Native: Built for a specific OS (Swift/Java). Fast and offline-friendly.
- Mobile Web: Websites accessed via a mobile browser.
- Hybrid: Web content inside a native wrapper (Cordova/React Native).
Hinglish: Native matlab jo sirf phone ke liye bani ho; Mobile Web matlab browser mein khulne wali site; Hybrid matlab donon ka mixture.
3. What are Desired Capabilities in Appium?
English: They are key-value pairs used to instruct the Appium server on which device and app to automate.
UiAutomator2Options options = new UiAutomator2Options();
options.setPlatformName("Android");
options.setDeviceName("emulator-5554");
options.setAppPackage("com.example.app");
options.setAppActivity(".MainActivity");
Advanced SQL for QA
1. Difference between INNER JOIN and LEFT JOIN?
English: Inner Join: Returns only matching rows. Left Join: Returns all rows from the left table and matching rows from the right.
Hinglish: Inner Join sirf matching data dikhata hai. Left Join left wali table ka poora data dikhaye chahe right mein match ho ya na ho. Practice SQL Queries in Lab
Hinglish: Inner Join sirf matching data dikhata hai. Left Join left wali table ka poora data dikhaye chahe right mein match ho ya na ho. Practice SQL Queries in Lab
2. How to find the 2nd highest salary in a table?
English: Using a subquery or the
OFFSET/LIMIT clause.SELECT MAX(Salary) FROM Employees WHERE Salary < (SELECT MAX(Salary) FROM Employees);Hinglish: Poore table se max salary nikalo jo main max salary se kam ho.