Introduction to Selenium
🔹 What is Selenium?
Selenium is an open-source automation tool used to automate web applications across different browsers and platforms.
📖 Nepali Insight:
Selenium भनेको browser खोल्ने, test steps automate गर्ने, र manually गर्ने कामलाई code बाट चलाउने automation tool हो।
✅ Key Features of Selenium
Feature | Description |
Open Source | Free and widely supported |
Browser Support | Chrome, Firefox, Edge, Safari |
Language Support | Java, Python, C#, JS, Ruby |
Framework Integration | TestNG, JUnit, Maven, Jenkins |
Cross-platform | Run on Windows, Mac, Linux |
Parallel Execution | With Selenium Grid |
🔹 Components of Selenium Suite
Component | Purpose |
Selenium WebDriver | Automates browser actions |
Selenium IDE | Record-playback browser extension |
Selenium Grid | Run tests on multiple machines/browsers |
Selenium RC (deprecated) | Old version, replaced by WebDriver |
✅ We focus on WebDriver for professional automation.
🔹 What Can You Automate with Selenium?
- Login, form input, navigation
- Dropdowns, alerts, file uploads
- Dynamic elements (AJAX, popups)
- Data-driven testing (from Excel/DB)
- End-to-end regression flows
🔹 What You Need to Start with Selenium (Java-Based)
Tool | Purpose |
Java | Programming language |
Eclipse or IntelliJ | IDE for writing code |
Maven | Dependency & project management |
Selenium WebDriver | Core automation tool |
ChromeDriver / GeckoDriver | Browser-specific drivers |
TestNG or JUnit | Test execution framework |
Browser | Chrome, Firefox, Edge, etc. |
✅ Real QA Example
Scenario: Test Login Page
java
CopyEdit
WebDriver driver = new ChromeDriver();
driver.get(“https://testsite.com”);
driver.findElement(By.id(“username”)).sendKeys(“Lok”);
driver.findElement(By.id(“password”)).sendKeys(“pass123”);
driver.findElement(By.id(“login”)).click();
📖 Nepali View:
Selenium ले browser खोलेर form भरेर login button click गर्यो — जस्तो QA manually गर्थे।
📘 Selenium Topic 2: Selenium WebDriver Architecture
🔹 What is WebDriver?
Selenium WebDriver is a core component of Selenium that provides APIs to interact directly with a web browser — just like a real user.
📖 Nepali Insight:
WebDriver ले browser लाई निर्देश दिन्छ — कुन element क्लिक गर्ने, कुन field मा लेख्ने आदि सबै browser-level action handle गर्छ।
✅ High-Level Architecture Overview
csharp
CopyEdit
[Your Test Script]
↓
[WebDriver API]
↓
[Browser Driver (ChromeDriver, GeckoDriver)]
↓
[Real Web Browser]
🔹 Components of WebDriver Architecture
Layer | Description |
Test Script | Java code written by QA to automate tests |
Selenium WebDriver API | Provides commands (click, sendKeys, get) |
Browser-Specific Driver | Converts API commands to browser-specific actions |
Real Browser | Browser like Chrome/Firefox where test runs |
🔹 Flow Explained Step-by-Step
- ✅ Test script sends command: driver.get(“https://gainsco.com”)
- ✅ WebDriver API translates it into HTTP request
- ✅ ChromeDriver.exe / geckodriver.exe receives the request
- ✅ Browser Driver uses JSON Wire Protocol / W3C Protocol to send commands to the browser
- ✅ Browser executes the action (open URL, click, enter text)
- ✅ Response comes back the same way
📖 Nepali Flow:
तपाईंले लेखेको code → WebDriver ले समझ्यो → Driver ले browser लाई command पठायो → browser ले काम गर्यो → result फर्कायो।
🔹 Browser Drivers and Their Role
Browser | Driver | Download Location |
Chrome | ChromeDriver | chromedriver.chromium.org |
Firefox | GeckoDriver | github.com/mozilla/geckodriver |
Edge | EdgeDriver | Microsoft Edge site |
Safari | Built-in SafariDriver | macOS only |
📌 All drivers must match the browser version and be in system path or project folder.
🔹 WebDriver Communication Protocols
Protocol | Description |
JSON Wire Protocol | Used in older Selenium versions |
W3C WebDriver Protocol | Used in Selenium 4+ |
✅ In Selenium 4, everything is W3C standard — more reliable and consistent.
🧪 QA-Friendly Real Use
java
CopyEdit
WebDriver driver = new ChromeDriver();
driver.get(“https://example.com”);
driver.findElement(By.id(“login”)).click();
- WebDriver API = driver.get()
- Browser driver = ChromeDriver
- Browser = Chrome opens site
🧠 Works on real browsers — so the testing is as close to a real user as possible.
✅ Summary Table
Component | Role |
Test Script | Java code you write |
WebDriver API | Middle layer |
Browser Driver | Converts API to browser-level commands |
Browser | Executes the actions (UI) |
Protocol | JSON Wire or W3C (communication format) |
📘 Selenium Topic 3: Setting Up a Selenium Project (Maven, Dependencies, Folder Structure)
🔹 Tools Needed
Tool | Purpose |
Java (JDK 8 or above) | Core language |
Eclipse / IntelliJ | IDE for writing code |
Maven | Build & dependency manager |
ChromeDriver | Browser driver |
Selenium WebDriver | Automation API |
TestNG or JUnit | Test framework |
✅ Step-by-Step Setup (Java + Maven + Selenium)
🔸 1. Create Maven Project in Eclipse
In Eclipse:
vbnet
CopyEdit
File → New → Project → Maven → Maven Project → Next
Choose archetype: maven-archetype-quickstart → Finish
📁 Default folder structure:
bash
CopyEdit
project-name/
└── src/
├── main/java → App code (not used for Selenium)
└── test/java → Test cases here
└── pom.xml → Project config file
🔸 2. Add Selenium & TestNG Dependencies to pom.xml
xml
CopyEdit
<dependencies>
<!– Selenium Java –>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<!– TestNG (or JUnit) –>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
</dependencies>
🧠 Maven will automatically download JAR files into your project’s classpath.
🔸 3. Add ChromeDriver to System
- Download from: https://chromedriver.chromium.org/downloads
- Place .exe inside drivers/ folder (optional) or system PATH
java
CopyEdit
System.setProperty(“webdriver.chrome.driver”, “drivers/chromedriver.exe”);
WebDriver driver = new ChromeDriver();
✅ You can also skip System.setProperty() by using WebDriverManager (covered later).
🔸 4. Write a Simple Selenium Test
Create a Java class under src/test/java:
java
CopyEdit
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class LoginTest {
@Test
public void testLogin() {
WebDriver driver = new ChromeDriver();
driver.get(“https://example.com/login”);
driver.findElement(By.id(“username”)).sendKeys(“Lok”);
driver.findElement(By.id(“password”)).sendKeys(“pass123”);
driver.findElement(By.id(“login”)).click();
driver.quit();
}
}
🔸 5. Run Using TestNG (Right-click → Run As → TestNG Test)
✅ Output will show in console with pass/fail report.
🔹 Project Folder Structure for POM
bash
CopyEdit
project-name/
├── drivers/ → ChromeDriver.exe, etc.
├── src/
│ ├── main/java → (usually empty)
│ └── test/java/
│ ├── base/ → Browser setup, TestBase
│ ├── pages/ → Page Object classes
│ ├── tests/ → Test classes (TestNG)
│ └── utils/ → Reusable utilities
├── test-output/ → TestNG reports
└── pom.xml → Maven file (dependencies)
✅ Summary
Step | Task |
1 | Create Maven project |
2 | Add Selenium + TestNG dependencies in pom.xml |
3 | Set up ChromeDriver |
4 | Write test in src/test/java |
5 | Run via TestNG |
📘 Selenium Topic 4: Locators in Selenium (id, name, xpath, cssSelector, linkText)
🔹 What Are Locators?
Locators are used to find and interact with web elements (buttons, textboxes, links, etc.) on a webpage.
📖 Nepali Insight:
Locator भन्नाले browser मा कुन element लाई click गर्न, लेख्न वा पढ्न हो — त्यो चिनाउने तरिका हो।
✅ Types of Locators in Selenium
Locator Type | Method | Usage |
id | By.id(“value”) | Fastest and preferred |
name | By.name(“value”) | Often used for forms |
className | By.className(“value”) | When class is unique |
tagName | By.tagName(“input”) | Less used |
linkText | By.linkText(“Exact Text”) | Full visible link text |
partialLinkText | By.partialLinkText(“Part”) | Partial match |
cssSelector | By.cssSelector(“pattern”) | Fast, powerful |
xpath | By.xpath(“expression”) | Most flexible, but slower |
🔸 1. id Locator
java
CopyEdit
driver.findElement(By.id(“username”)).sendKeys(“Lok”);
✅ Use when ID is unique and present (fastest method).
🔸 2. name Locator
java
CopyEdit
driver.findElement(By.name(“email”)).sendKeys(“lok@test.com”);
✅ Commonly used in forms and login pages.
🔸 3. className Locator
java
CopyEdit
driver.findElement(By.className(“input-class”)).click();
⚠️ Only works if class name is single and unique (not multiple classes like btn primary).
🔸 4. linkText and partialLinkText
✅ For anchor <a> tags only.
java
CopyEdit
driver.findElement(By.linkText(“Forgot Password?”)).click();
driver.findElement(By.partialLinkText(“Forgot”)).click();
📖 Use when link text is visible and readable.
🔸 5. cssSelector – Fast and Powerful
java
CopyEdit
driver.findElement(By.cssSelector(“input[type=’email’]”)).sendKeys(“lok@test.com”);
driver.findElement(By.cssSelector(“#username”)).sendKeys(“Lok”); // ID selector
driver.findElement(By.cssSelector(“.btn-primary”)).click(); // Class selector
📖 Nepali Tip:
CSS selectors use HTML pattern, and are faster than XPath in most cases.
🔸 6. xpath – Flexible and Most Powerful
java
CopyEdit
driver.findElement(By.xpath(“//input[@id=’username’]”)).sendKeys(“Lok”);
driver.findElement(By.xpath(“//button[text()=’Login’]”)).click();
driver.findElement(By.xpath(“//div[@class=’card’]//span”)).click();
✅ Use for:
- Parent-child structure
- Complex conditions
- Dynamic elements
📌 Absolute XPath: /html/body/div[2]/form[1]/input[1] ❌ Avoid
📌 Relative XPath: //input[@type=’text’] ✅ Preferred
🧠 When to Use What?
Locator | Use When |
id | Always use first if available |
name | Next best for inputs |
cssSelector | Fast, flexible |
xpath | Complex DOM, dynamic data |
linkText | For full visible links |
className | If unique & single class |
✅ Summary Table
Locator | Syntax | Use Case |
id | By.id(“id”) | Fastest, unique |
name | By.name(“name”) | Forms |
className | By.className(“value”) | Single class |
cssSelector | By.cssSelector(“pattern”) | Fast + readable |
xpath | By.xpath(“//tag[@attr=’val’]”) | Most powerful |
linkText | By.linkText(“Full Text”) | Full clickable links |
partialLinkText | By.partialLinkText(“Part”) | Partial clickable links |
📘 Selenium Topic 5: XPath Axes, Functions & Dynamic XPath
🔹 Why XPath?
XPath is used to locate elements in complex or dynamic HTML structures when id, name, or simple CSS locators are not sufficient.
📖 Nepali Insight:
XPath ले page को structure अनुसार element को बाटो खोज्छ — जटिल HTML मा XPath नै सही तरीका हो।
🔸 XPath Syntax Recap
Type | Syntax | Example |
Absolute | /html/body/div[1]/input | ❌ Avoid |
Relative | //tag[@attr=’value’] | ✅ //input[@id=’email’] |
✅ Common XPath Functions
Function | Use | Example |
text() | Match exact text | //a[text()=’Login’] |
contains() | Partial match | //div[contains(text(), ‘Hello’)] |
starts-with() | Beginning match | //input[starts-with(@id,’user’)] |
last() | Last element in list | (//button)[last()] |
position() | Specific index | (//input[@type=’text’])[2] |
📖 Nepali Tip:
contains() ले partial match गर्दा काम गर्छ, जुन dynamic attributes मा use हुन्छ।
🔹 Dynamic XPath
Dynamic XPath is useful when element attributes keep changing or are partially dynamic (like id=login_123, login_456).
✅ Example:
java
CopyEdit
//input[contains(@id,’login_’)]
📌 Also works with text:
java
CopyEdit
//a[contains(text(),’Forgot’)]
🔹 XPath with Multiple Conditions
java
CopyEdit
//input[@type=’text’ and @name=’username’]
✅ Use and / or to combine multiple attributes.
✅ XPath Axes – Traverse the DOM
XPath axes allow us to navigate around the element tree, e.g., parent, child, sibling.
Axis | Description | Example |
parent:: | Select parent of element | //input[@id=’email’]/parent::div |
child:: | Direct children | //ul/child::li |
ancestor:: | Go to upper tree | //span/ancestor::div |
descendant:: | All nested elements | //div[@id=’main’]/descendant::input |
following:: | Elements after current node | //label[text()=’Email’]/following::input |
preceding:: | Elements before current node | //input[@id=’email’]/preceding::label |
following-sibling:: | Same-level next node | //label[text()=’Email’]/following-sibling::input |
🔹 Example: Real Dynamic XPath Use
You want to click on the delete icon beside a specific user in a table:
java
CopyEdit
//td[text()=’Lok’]/following-sibling::td//button[@class=’delete’]
✅ This selects the delete button in the same row where text is Lok.
🔹 Tips for XPath Writing
Tip | Description |
Use contains() | For dynamic attribute values |
Use starts-with() | If prefix is fixed |
Prefer text() | For clickable links/buttons |
Avoid absolute paths | They break easily |
Use Axes | For table-based or nested elements |
✅ Summary Table
Topic | Example | Use |
text() | //h2[text()=’Welcome’] | Exact match |
contains() | //a[contains(text(),’Login’)] | Partial |
axes | following-sibling::, ancestor:: | Navigate tree |
position() | (//input)[2] | By index |
last() | (//div)[last()] | Last element |
Dynamic ID | //input[contains(@id,’user_’)] | Handle changing values |
📘 Selenium Topic 6: Handling Dropdowns, Checkboxes, Radio Buttons, Hyperlinks, iFrames, Window Handles, and Pagination
🔹 1. Handling Dropdowns (Select tags only)
📖 Nepali Insight:
Dropdown भन्ने element मा Selenium ले Select class प्रयोग गर्छ।
✅ Java Code:
java
CopyEdit
import org.openqa.selenium.support.ui.Select;
WebElement dropdown = driver.findElement(By.id(“country”));
Select select = new Select(dropdown);
select.selectByVisibleText(“Nepal”);
select.selectByIndex(2);
select.selectByValue(“NP”);
✅ Methods:
- selectByVisibleText()
- selectByIndex()
- selectByValue()
🔹 2. Checkboxes
✅ Select checkbox (if not already selected):
java
CopyEdit
WebElement checkbox = driver.findElement(By.id(“agree”));
if (!checkbox.isSelected()) {
checkbox.click();
}
📌 Use .isSelected() to verify current state.
🔹 3. Radio Buttons
✅ Similar to checkboxes:
java
CopyEdit
WebElement male = driver.findElement(By.id(“male”));
if (!male.isSelected()) {
male.click();
}
✅ To select by value:
java
CopyEdit
List<WebElement> radios = driver.findElements(By.name(“gender”));
for (WebElement r : radios) {
if (r.getAttribute(“value”).equals(“Male”)) {
r.click();
break;
}
}
🔹 4. Hyperlinks
✅ Click using By.linkText() or By.partialLinkText():
java
CopyEdit
driver.findElement(By.linkText(“Privacy Policy”)).click();
✅ Validate link text:
java
CopyEdit
String linkText = driver.findElement(By.xpath(“//a”)).getText();
System.out.println(linkText);
🔹 5. iFrame Handling
📖 Nepali Tip:
Page भित्र अर्को HTML document लाई iFrame भनिन्छ। Switch गर्नु पर्छ।
✅ Switch to iFrame:
java
CopyEdit
driver.switchTo().frame(“iframeName”);
// or by index: driver.switchTo().frame(0);
✅ After interaction:
java
CopyEdit
driver.switchTo().defaultContent(); // switch back to main page
🔹 6. Window/Tab Handling
✅ Get current window ID:
java
CopyEdit
String mainWindow = driver.getWindowHandle();
✅ Switch to new window:
java
CopyEdit
Set<String> handles = driver.getWindowHandles();
for (String handle : handles) {
if (!handle.equals(mainWindow)) {
driver.switchTo().window(handle);
}
}
✅ Switch back:
java
CopyEdit
driver.switchTo().window(mainWindow);
📌 Use for popups, new tabs, external links.
🔹 7. Pagination Handling
📖 Nepali View:
Pagination ले धेरै data लाई page-wise देखाउँछ — test गर्न loop गर्नुपर्छ।
✅ Example (next button loop):
java
CopyEdit
while (true) {
// perform action on current page
List<WebElement> items = driver.findElements(By.className(“item”));
WebElement next = driver.findElement(By.xpath(“//a[text()=’Next’]”));
if (next.isDisplayed()) {
next.click();
} else {
break;
}
}
🔹 8. Scroll Page (JavaScriptExecutor)
✅ Scroll to element:
java
CopyEdit
WebElement el = driver.findElement(By.id(“footer”));
((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView(true);”, el);
✅ Scroll full page:
java
CopyEdit
((JavascriptExecutor) driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”);
🔹 9. Tooltip Handling
✅ Get tooltip text from title attribute:
java
CopyEdit
String tooltip = driver.findElement(By.id(“info”)).getAttribute(“title”);
✅ Summary Table
Element | Action |
Dropdown | Select class (selectByText/Index/Value) |
Checkbox | isSelected(), then click() |
Radio | Same as checkbox |
Link | click(), getText() |
iFrame | switchTo().frame(), defaultContent() |
New Window/Tab | getWindowHandles(), switchTo().window() |
Pagination | Loop + click Next |
Scroll | JavascriptExecutor |
Tooltip | getAttribute(“title”) |
📘 Selenium Topic 7: Waits in Selenium (Implicit, Explicit, Fluent)
🔹 Why Waits Are Important?
Web elements often take time to load, especially on dynamic or slow applications (AJAX, JavaScript-heavy). Waits allow your script to pause and wait for the right moment before acting.
📖 Nepali Insight:
Wait ले Selenium लाई भनिन्छ — “element loaded नभएसम्म पर्ख”।
✅ Types of Waits in Selenium WebDriver
Type | Applied On | Description |
Implicit Wait | Globally | Waits for a fixed time before failing |
Explicit Wait | For specific elements | Waits until condition is true |
Fluent Wait | Like explicit + polling | Advanced wait with polling and custom timeout |
🔸 1. Implicit Wait
- Set once → applies to all elements
- Not efficient for dynamic elements
java
CopyEdit
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
📖 Meaning: Selenium will wait up to 10 seconds before throwing NoSuchElementException.
🔸 2. Explicit Wait
- Waits for specific condition to be met (visibility, clickable, presence)
- Uses WebDriverWait and ExpectedConditions
java
CopyEdit
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id(“submit”)));
button.click();
✅ Common Conditions:
java
CopyEdit
ExpectedConditions.visibilityOfElementLocated()
ExpectedConditions.elementToBeClickable()
ExpectedConditions.titleContains()
ExpectedConditions.invisibilityOfElementLocated()
🔸 3. Fluent Wait
- Similar to Explicit Wait, but allows:
- Custom polling interval
- Ignore specific exceptions
java
CopyEdit
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement element = fluentWait.until(driver -> driver.findElement(By.id(“dynamic”)));
📖 Nepali View:
Fluent wait ले Selenium लाई भन्छ — “हरेक 2 sec मा check गर, 20 sec सम्म try गर”।
🔹 When to Use What?
Use Case | Wait Type |
General UI load | Implicit |
Specific AJAX call | Explicit |
Retry with polling | Fluent |
🧠 QA Tips
- Avoid using Thread.sleep() — it’s static and slows your tests unnecessarily
- Prefer WebDriverWait for dynamic apps
- Fluent Wait is great for retry logic in unstable apps
✅ Summary Table
Wait | Scope | Flexibility | Example |
Implicit | Global | ❌ Fixed time | implicitlyWait(10) |
Explicit | Per element | ✅ Condition-based | WebDriverWait + ExpectedConditions |
Fluent | Per element | ✅ + polling | FluentWait().pollingEvery() |
📘 Selenium Topic 8: Handling Alerts, Pop-ups, and File Upload/Download
🔹 Why This Matters?
Modern web apps often include JavaScript alerts, custom modals, and file operations. As a QA engineer, automating these interactions is crucial.
📖 Nepali Insight:
Browser ले देखाउने message box (Alert), file choose गर्नुपर्ने Upload box, वा Download गर्नुपर्ने task हरु Selenium बाट deal गर्न सिक्नैपर्छ।
✅ 1. Handling JavaScript Alerts (Simple, Confirm, Prompt)
🔸 Switch to Alert
java
CopyEdit
Alert alert = driver.switchTo().alert();
🔸 Handle Different Types
Type | Action |
Simple Alert | alert.accept(); |
Confirmation Alert | alert.dismiss(); or accept(); |
Prompt Alert | alert.sendKeys(“Test”); alert.accept(); |
📖 Example:
java
CopyEdit
driver.switchTo().alert().accept();
✅ 2. Handling Custom Pop-ups (Not JavaScript Alerts)
- Custom HTML modals require normal WebDriver locators
java
CopyEdit
driver.findElement(By.className(“modal-close”)).click();
📌 Check if modal is present:
java
CopyEdit
boolean popup = driver.findElement(By.id(“popup”)).isDisplayed();
✅ Use Explicit Wait if it’s dynamically loaded.
✅ 3. File Upload
You can’t interact with system file explorer directly via click. Use sendKeys() to upload.
java
CopyEdit
WebElement uploadBtn = driver.findElement(By.id(“upload”));
uploadBtn.sendKeys(“C:\\Users\\Lok\\Desktop\\resume.pdf”);
📌 Works only if the element is <input type=”file”>
✅ 4. File Download Handling
Java cannot interact with browser-level “Save as” dialog. So we handle download by:
🔸 Option 1: Pre-set browser download folder
Set preferences in ChromeOptions:
java
CopyEdit
HashMap<String, Object> prefs = new HashMap<>();
prefs.put(“download.default_directory”, “C:\\Downloads”);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption(“prefs”, prefs);
WebDriver driver = new ChromeDriver(options);
📌 Automatically downloads file to specified path.
🔸 Option 2: Use Robot Class (for native dialogs – advanced)
For cases where you must interact with OS dialog (not preferred):
java
CopyEdit
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
🔸 Option 3: Download Verification (Check if file exists)
java
CopyEdit
File file = new File(“C:\\Downloads\\file.txt”);
if (file.exists()) {
System.out.println(“Download Success”);
}
✅ Summary Table
Task | Technique |
Alert | switchTo().alert().accept() |
Confirm | alert.dismiss() |
Prompt | alert.sendKeys() |
Modal Popup | findElement().click() |
Upload File | sendKeys(“path”) to input element |
Download File | Use ChromeOptions + verify with Java IO |
📘 Selenium Topic 9: TestNG Framework (Annotations, Groups, XML)
🔹 What is TestNG?
TestNG (Test Next Generation) is a testing framework for Java, designed to simplify:
- Test execution
- Grouping tests
- Parallel runs
- Reporting
📖 Nepali Insight:
TestNG भनेको Java testing framework हो जसले test case लाई organize, run, र manage गर्न सजिलो बनाउँछ।
✅ Why Use TestNG with Selenium?
Benefit | Description |
Structured testing | Use @Test, @BeforeMethod, @AfterMethod |
Grouping & prioritizing | Control which tests to run |
Parallel execution | Run tests faster |
Report generation | Automatic HTML reports |
Flexible configuration | testng.xml for setup |
🔸 1. TestNG Annotations
Annotation | Purpose |
@Test | Marks a method as a test |
@BeforeSuite | Runs once before all tests in the suite |
@BeforeTest | Runs before <test> tag in XML |
@BeforeClass | Runs once before first method in class |
@BeforeMethod | Runs before each @Test method |
@AfterMethod | Runs after each @Test method |
@AfterClass | Runs once after last test in class |
@AfterSuite | Runs after all tests in the suite |
✅ Example:
java
CopyEdit
public class LoginTest {
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
}
@Test
public void validLogin() {
driver.get(“https://example.com”);
driver.findElement(By.id(“user”)).sendKeys(“Lok”);
driver.findElement(By.id(“pass”)).sendKeys(“1234”);
driver.findElement(By.id(“login”)).click();
}
@AfterMethod
public void teardown() {
driver.quit();
}
}
🔸 2. Grouping and Prioritizing Tests
✅ Group example:
java
CopyEdit
@Test(groups = “smoke”)
public void quickCheck() { }
@Test(groups = “regression”)
public void fullFlowTest() { }
✅ Priority example:
java
CopyEdit
@Test(priority = 1)
public void openBrowser() { }
@Test(priority = 2)
public void login() { }
📌 Lower number = higher priority.
🔸 3. testng.xml – Configuration File
📖 Used to define:
- Which classes to run
- Group filters
- Parallel execution
- Include/exclude tests
✅ Sample testng.xml:
xml
CopyEdit
<!DOCTYPE suite SYSTEM “https://testng.org/testng-1.0.dtd” >
<suite name=”Regression Suite”>
<test name=”Login Tests”>
<classes>
<class name=”tests.LoginTest”/>
<class name=”tests.SignupTest”/>
</classes>
</test>
</suite>
✅ Run via:
Right-click testng.xml → Run As → TestNG Suite
✅ TestNG Reports
After execution, reports are generated automatically:
bash
CopyEdit
/test-output/index.html
📌 View pass/fail summary, exceptions, logs.
🔸 Useful TestNG Annotations for QA Projects
Annotation | Where | Purpose |
@Parameters | Test method | Inject data from XML |
@DataProvider | For DDT | Return test data in array |
dependsOnMethods | Test chaining | Run test only if another passes |
enabled=false | Any test | Skip test temporarily |
✅ Summary Table
Feature | Syntax | Use |
Mark test | @Test | Any method |
Setup/teardown | @BeforeMethod, @AfterMethod | WebDriver open/close |
Group tests | @Test(groups=”smoke”) | Run selected tests |
Prioritize | @Test(priority=1) | Control test order |
XML config | testng.xml | Manage suites and parallelism |
📘 Selenium Topic 10: TestNG DataProvider and Parameterization (Excel, JSON, XML driven)
🔹 Why Parameterization?
Parameterization helps you run the same test case multiple times with different data — without duplicating code.
📖 Nepali Insight:
Parameterization ले एउटै test case different inputs ले चलाउने सुविधा दिन्छ — यो Data-Driven Testing को foundation हो।
✅ 1. DataProvider in TestNG
DataProvider is TestNG’s built-in feature to pass multiple sets of data to the same test method.
🔸 Basic Example:
java
CopyEdit
@DataProvider(name = “loginData”)
public Object[][] loginDataProvider() {
return new Object[][] {
{“user1”, “pass1”},
{“user2”, “pass2”}
};
}
@Test(dataProvider = “loginData”)
public void loginTest(String username, String password) {
System.out.println(“Username: ” + username + “, Password: ” + password);
}
✅ Output:
yaml
CopyEdit
Username: user1, Password: pass1
Username: user2, Password: pass2
📌 Best for testing forms, login, or any input-driven test.
✅ 2. Parameterization Using testng.xml
You can pass parameters directly from XML using @Parameters.
java
CopyEdit
@Parameters({“browser”, “url”})
@Test
public void openBrowser(String browser, String url) {
System.out.println(“Browser: ” + browser);
System.out.println(“URL: ” + url);
}
🧾 In testng.xml:
xml
CopyEdit
<suite name=”Browser Suite”>
<parameter name=”browser” value=”chrome”/>
<parameter name=”url” value=”https://example.com”/>
<test name=”Test”>
<classes>
<class name=”tests.BrowserTest”/>
</classes>
</test>
</suite>
📌 Use this when managing environment configs or cross-browser testing.
✅ 3. Excel Parameterization (Apache POI)
You can read data from Excel and return it to DataProvider.
java
CopyEdit
@DataProvider(name = “excelData”)
public Object[][] readExcel() throws Exception {
FileInputStream file = new FileInputStream(“data.xlsx”);
Workbook wb = WorkbookFactory.create(file);
Sheet sheet = wb.getSheet(“Sheet1”);
int rows = sheet.getLastRowNum();
Object[][] data = new Object[rows][2];
for (int i = 1; i <= rows; i++) {
data[i-1][0] = sheet.getRow(i).getCell(0).getStringCellValue();
data[i-1][1] = sheet.getRow(i).getCell(1).getStringCellValue();
}
return data;
}
📌 Use for large test suites where business users maintain data.
✅ 4. JSON Parameterization (Simple JSON / Jackson)
✅ Read values from JSON:
java
CopyEdit
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(“testdata.json”));
JSONObject data = (JSONObject) obj;
String username = data.get(“user”).toString();
🧠 Combine with DataProvider for full control.
✅ 5. Parameterization Using CSV / TXT
✅ Read using BufferedReader:
java
CopyEdit
BufferedReader br = new BufferedReader(new FileReader(“data.txt”));
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(“,”);
}
📌 Works well for lightweight data.
✅ Summary Table
Source | How to Use | Best For |
@DataProvider | Java method returning Object[][] | Simple inline test data |
@Parameters + XML | testng.xml values | Config-based test inputs |
Excel | Apache POI | Large test data sheets |
JSON | JSON.simple, Jackson | API testing, configs |
CSV/TXT | Java IO | Lightweight input files |
🧪 QA Usage Examples
Use Case | Technique |
Login forms with 10 users | DataProvider |
Browser/environment | @Parameters from XML |
Complex insurance data | Excel-driven POI |
API payload values | JSON parameterization |
List of cities, dates, etc. | CSV or plain text |
📘 Selenium Topic 11: Page Object Model (POM) with TestNG
🔹 What is Page Object Model (POM)?
POM is a design pattern in Selenium where each web page is represented as a Java class, and the elements + actions of the page are defined in that class.
📖 Nepali Insight:
POM ले तपाईंको code लाई organize गर्छ — हर एक webpage को लागि अलग Java class बनाउने, जसमा fields र action method हुन्छन्।
✅ Benefits of POM
Benefit | Description |
Reusability | Reuse locators/methods across tests |
Maintainability | Update only in one place if UI changes |
Readability | Code looks like natural language (e.g., loginPage.login()) |
Scalability | Easy to add more tests/pages |
🔹 POM Structure
📁 Folder view:
csharp
CopyEdit
project/
├── pages/
│ ├── LoginPage.java
│ ├── HomePage.java
├── tests/
│ ├── LoginTest.java
├── base/
│ ├── TestBase.java
└── pom.xml
✅ Step-by-Step POM Setup
🔸 1. Create Base Class (TestBase.java)
java
CopyEdit
public class TestBase {
public WebDriver driver;
@BeforeMethod
public void setUp() {
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(“https://example.com”);
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
🔸 2. Create Page Class (LoginPage.java)
java
CopyEdit
public class LoginPage {
WebDriver driver;
// Constructor
public LoginPage(WebDriver driver) {
this.driver = driver;
}
// Locators
By username = By.id(“user”);
By password = By.id(“pass”);
By loginBtn = By.id(“login”);
// Actions
public void login(String user, String pass) {
driver.findElement(username).sendKeys(user);
driver.findElement(password).sendKeys(pass);
driver.findElement(loginBtn).click();
}
}
📖 Nepali View:
LoginPage.java मा field (username, password) र action (login()) define गरिन्छ।
🔸 3. Create Test Class (LoginTest.java)
java
CopyEdit
public class LoginTest extends TestBase {
@Test
public void testValidLogin() {
LoginPage loginPage = new LoginPage(driver);
loginPage.login(“Lok”, “pass123”);
Assert.assertEquals(driver.getTitle(), “Dashboard”);
}
}
✅ Test is readable, reusable, and robust.
🔹 Advanced: PageFactory (Optional)
Use annotations to initialize elements:
java
CopyEdit
public class LoginPage {
@FindBy(id = “user”) WebElement username;
@FindBy(id = “pass”) WebElement password;
@FindBy(id = “login”) WebElement loginBtn;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void login(String u, String p) {
username.sendKeys(u);
password.sendKeys(p);
loginBtn.click();
}
}
✅ Use PageFactory.initElements() for automatic element binding.
✅ Summary Table
Component | Location | Role |
TestBase.java | base/ | Driver setup & teardown |
LoginPage.java | pages/ | Page fields and actions |
LoginTest.java | tests/ | Test case logic |
pom.xml | root | Dependencies |
🧪 QA Project Benefits of POM
- Maintain large UI regression suites
- Share common page actions across hundreds of tests
- Integrate smoothly with TestNG, Excel, JSON, Jenkins
📘 Selenium Topic 12: TestNG Assertions and Reporting (HardAssert, SoftAssert, Logs, Reports)
🔹 Why Assertions?
Assertions in TestNG are used to compare actual results with expected results.
📖 Nepali Insight:
Assert ले check गर्छ — “हामीले पाएको result सही हो कि होइन?”
✅ 1. Hard Assertions (org.testng.Assert)
- Test stops immediately if assertion fails
🔸 Common Methods:
java
CopyEdit
Assert.assertEquals(actual, expected);
Assert.assertTrue(condition);
Assert.assertFalse(condition);
Assert.assertNotNull(object);
🔸 Example:
java
CopyEdit
Assert.assertEquals(driver.getTitle(), “Dashboard”, “Title mismatch!”);
📌 If it fails → Test stops → Error shown in report.
✅ 2. Soft Assertions (org.testng.asserts.SoftAssert)
- Continues execution even after failure
- Must call .assertAll() at the end to collect results
🔸 Example:
java
CopyEdit
SoftAssert soft = new SoftAssert();
soft.assertEquals(“Lok”, “Luk”); // Will fail
soft.assertTrue(5 < 3); // Will fail
soft.assertAll(); // Collects all failed asserts
📖 Nepali Tip:
SoftAssert ले सबै test run गर्न दिन्छ अनि अन्त्यमा report गर्छ कुन-कुन fail भए।
✅ 3. Assert vs Verify (Conceptual)
Term | Stops test? | Used when |
Assert | Yes | Critical failure |
SoftAssert | No | Optional checks |
Verify (custom) | No | Log result but keep testing |
✅ 4. Logging in TestNG
✅ Basic log in console:
java
CopyEdit
System.out.println(“Step 1: Logged in successfully”);
✅ Using Reporter class (visible in TestNG HTML report):
java
CopyEdit
Reporter.log(“Step passed: Login button clicked”);
✅ 5. TestNG HTML Reports
📁 After running tests:
lua
CopyEdit
project/
└── test-output/
└── index.html
📌 Report includes:
- Summary of passed/failed tests
- Error logs
- Execution time
- Class/method view
✅ 6. Customizing Reports (optional)
Use ITestListener or external plugins like:
- Extent Reports
- Allure Reports
🧪 Useful for client demos and management dashboards.
✅ Summary Table
Feature | Class/Tool | Usage |
Hard Assertion | Assert | Stops test on failure |
Soft Assertion | SoftAssert | Logs all failures after .assertAll() |
Logs | System.out.println() / Reporter.log() | Debug/test progress |
Report | test-output/index.html | HTML result summary |
Advanced Report | Extent, Allure | Beautiful dashboards |
📘 Selenium Topic 13: Cross-Browser Testing with TestNG and WebDriver
🔹 What is Cross-Browser Testing?
Running your test scripts across multiple browsers (Chrome, Firefox, Edge, etc.) to ensure that the application works consistently.
📖 Nepali Insight:
Cross-browser testing भन्नाले एउटै test case Chrome, Firefox, Edge आदि browsers मा चलाउने कुरा हो।
✅ Why Cross-Browser Testing?
Reason | Benefit |
Browser compatibility | Ensure UI and functionality behave the same |
Real-world coverage | Simulates how different users access your site |
Bug identification | Catch browser-specific bugs early |
✅ Required Setup
Browser | Driver Required |
Chrome | ChromeDriver |
Firefox | GeckoDriver |
Edge | EdgeDriver |
📌 Ensure drivers match the installed browser version.
🔸 1. WebDriver Setup with If-Else Logic (Single Class)
java
CopyEdit
WebDriver driver;
@BeforeMethod
@Parameters(“browser”)
public void setup(String browser) {
if (browser.equalsIgnoreCase(“chrome”)) {
driver = new ChromeDriver();
} else if (browser.equalsIgnoreCase(“firefox”)) {
driver = new FirefoxDriver();
} else if (browser.equalsIgnoreCase(“edge”)) {
driver = new EdgeDriver();
}
driver.manage().window().maximize();
}
🔸 2. testng.xml for Multiple Browsers
xml
CopyEdit
<suite name=”CrossBrowserSuite” parallel=”tests”>
<test name=”ChromeTest”>
<parameter name=”browser” value=”chrome”/>
<classes>
<class name=”tests.LoginTest”/>
</classes>
</test>
<test name=”FirefoxTest”>
<parameter name=”browser” value=”firefox”/>
<classes>
<class name=”tests.LoginTest”/>
</classes>
</test>
<test name=”EdgeTest”>
<parameter name=”browser” value=”edge”/>
<classes>
<class name=”tests.LoginTest”/>
</classes>
</test>
</suite>
✅ This runs the same test class (LoginTest) in parallel on multiple browsers.
✅ Tips for Stable Cross-Browser Testing
Tip | Description |
Use WebDriverManager | Auto-manages driver versions |
Avoid browser-specific XPath | Use CSS or stable attributes |
Add waits | Handle rendering speed differences |
Run in headless mode | For CI/CD pipelines |
🔸 Optional: Using WebDriverManager (No manual driver setup)
java
CopyEdit
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
📌 Add WebDriverManager dependency in pom.xml:
xml
CopyEdit
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.5.3</version>
</dependency>
✅ Summary Table
Feature | Tool/Code |
Multi-browser support | testng.xml with <parameter name=”browser”/> |
Driver logic | if-else or switch-case in setup method |
Parallel execution | <suite parallel=”tests”> |
Auto driver handling | WebDriverManager |
Supported browsers | Chrome, Firefox, Edge, Safari |
📘 Selenium Topic 14: Parallel Test Execution with TestNG and Grid
🔹 What is Parallel Execution?
Running multiple tests at the same time on:
- Different browsers
- Different machines
- Different environments
📖 Nepali Insight:
Parallel execution भन्नाले एउटै समयमा धेरै browser/test case चलाउने — जसले testing time घटाउँछ।
✅ 1. Parallel Execution Using Only TestNG (testng.xml)
🔸 Step-by-Step
✅ testng.xml with parallel=”methods”
xml
CopyEdit
<suite name=”ParallelSuite” parallel=”methods” thread-count=”3″>
<test name=”ParallelTest”>
<classes>
<class name=”tests.LoginTest”/>
</classes>
</test>
</suite>
Option | Meaning |
parallel=”methods” | Run test methods of same class in parallel |
parallel=”tests” | Run test classes in parallel |
thread-count=”X” | Number of parallel threads (tests running at once) |
📌 Make sure each test method uses independent WebDriver instance.
✅ 2. Parallel Execution with Selenium Grid (Across Machines)
Selenium Grid allows you to run tests on different machines and OS/browser combinations.
🔸 Grid Components
Component | Role |
Hub | Central controller |
Node | Executes test on a machine/browser |
🔸 Step-by-Step for Grid (Selenium 4)
✅ Start Selenium Grid Hub & Node (Local)
- Download Selenium Standalone Server or run via Docker
- Launch Selenium Hub & Node:
bash
CopyEdit
java -jar selenium-server-4.10.0.jar hub
java -jar selenium-server-4.10.0.jar node –hub http://localhost:4444
✅ Update Code to Use RemoteWebDriver
java
CopyEdit
WebDriver driver = new RemoteWebDriver(
new URL(“http://localhost:4444/wd/hub”),
new ChromeOptions()
);
🧠 Use ChromeOptions, FirefoxOptions as needed
✅ Combine Grid + TestNG
- Use @Parameters(“browser”)
- testng.xml passes browser + Grid runs on matching node
✅ Best Practices
Tip | Description |
Use thread-safe driver | Don’t reuse same WebDriver across threads |
Manage drivers carefully | Close after each method |
Scale nodes for real load | 1 node per browser version |
Use ExtentReport or Allure | Merge reports after parallel runs |
✅ Summary Table
Technique | Tools |
Parallel in same machine | testng.xml + thread-count |
Cross-machine execution | Selenium Grid |
Parallel methods | parallel=”methods” |
Parallel browsers | Nodes with Chrome, Firefox, etc. |
Thread safety | Use ThreadLocal<RemoteWebDriver> (advanced) |
📘 Selenium Topic 15: Framework Design Strategy
(Maven + POM + TestNG + Data-Driven Testing + Jenkins)
🔹 Why Design a Framework?
📖 Nepali Insight:
Framework ले तपाईंको automation लाई organized, reusable, scalable बनाउँछ — जसले टीम level मा काम गर्न सजिलो बनाउँछ।
✅ Benefits:
- Easy maintenance
- Reusable test logic
- Reporting and CI/CD-ready
- Supports scaling (cross-browser, multi-env)
✅ Framework Structure Overview
bash
CopyEdit
project-root/
├── pom.xml
├── drivers/
├── test-output/
├── src/
│ ├── main/java/
│ │ ├── pages/ → Page Objects
│ │ ├── base/ → TestBase (setup/teardown)
│ │ ├── utils/ → ExcelUtils, Waits, ConfigReader
│ └── test/java/
│ ├── tests/ → Test classes with @Test
│ └── resources/ → Test data (.xlsx, .json)
🔸 1. Maven for Dependency Management
✅ pom.xml includes:
xml
CopyEdit
<dependencies>
<!– Selenium –>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<!– TestNG –>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
<!– WebDriverManager (Optional) –>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.5.3</version>
</dependency>
</dependencies>
🔸 2. Page Object Model (POM)
✅ Create a Java class for each web page
Example: LoginPage.java
java
CopyEdit
public class LoginPage {
WebDriver driver;
By user = By.id(“username”);
By pass = By.id(“password”);
By login = By.id(“login”);
public void login(String uname, String pword) {
driver.findElement(user).sendKeys(uname);
driver.findElement(pass).sendKeys(pword);
driver.findElement(login).click();
}
}
🔸 3. TestNG Integration
✅ Use annotations like:
java
CopyEdit
@BeforeMethod
@AfterMethod
@Test(priority=1, groups={“smoke”})
✅ Use testng.xml to organize test execution:
xml
CopyEdit
<suite name=”Regression Suite” parallel=”tests” thread-count=”2″>
<test name=”Login Test”>
<classes>
<class name=”tests.LoginTest”/>
</classes>
</test>
</suite>
🔸 4. Data-Driven Testing (DDT)
✅ Use @DataProvider or Excel/JSON file readers
java
CopyEdit
@Test(dataProvider=”loginData”)
public void loginTest(String user, String pass) {
loginPage.login(user, pass);
}
✅ External Excel file via Apache POI:
java
CopyEdit
ExcelUtils.readCell(“TestData.xlsx”, “Login”, 1, 0);
🔸 5. Jenkins Integration
✅ Steps:
- Install Jenkins
- Create a new job (freestyle or Maven)
- Source Code Management → GitHub Repo
- Build → mvn clean test
- Post-build → Email or Report archive
✅ Run automated tests via:
- Git commit hooks
- Daily schedule (cron)
- After every deployment (CI/CD)
✅ Extra Tools You Can Plug In
Tool | Purpose |
ExtentReports / Allure | Better visual reporting |
Log4j | Logging |
RestAssured | API test integration |
Docker + Grid | Scalable browser execution |
GitHub Actions | Cloud CI/CD |
✅ Summary Table
Component | Role |
Maven | Project build & dependency manager |
POM | Code organization (pages, base, tests) |
TestNG | Test control & reporting |
DDT | Excel, JSON, DataProvider |
Jenkins | Continuous test execution |
Optional | Reports, Logging, CI tools |
📘 1. Java OOPs Concepts in Page Object Model (POM)
🔹 🔸 OOPs Concept → Where It Appears in Selenium Framework
OOP Concept | Example in POM Framework |
Encapsulation | Page classes have private By locators + public methods to access them |
Inheritance | Test classes extend TestBase for setup/teardown |
Polymorphism | Method clickLogin() works differently in AdminPage vs UserPage |
Abstraction | Pages hide implementation (clicks, inputs) from test logic |
✅ Example:
java
CopyEdit
public class LoginPage {
private By user = By.id(“username”);
private By pass = By.id(“password”);
public void login(String u, String p) {
driver.findElement(user).sendKeys(u);
driver.findElement(pass).sendKeys(p);
}
}
📖 Test script just says: loginPage.login(“Lok”, “pass123”) → doesn’t worry how.
📘 2. Selenium Class Hierarchy in Framework
🔹 General Automation Hierarchy
vbnet
CopyEdit
TestNG Test Class (LoginTest.java)
↓ uses
Page Class (LoginPage.java)
↓ uses
WebDriver Actions
↓ uses
Locators from DOM
🔹 Folder Structure Example
arduino
CopyEdit
project/
├── base/ → TestBase.java (WebDriver setup)
├── pages/ → LoginPage.java, HomePage.java
├── tests/ → LoginTest.java
├── utils/ → ExcelUtils, Waits, ConfigReader
🔹 Selenium API Class Hierarchy
vbnet
CopyEdit
WebDriver (Interface)
↳ RemoteWebDriver (Class)
↳ ChromeDriver / FirefoxDriver / EdgeDriver
Class | Use |
WebDriver | Interface for all browser drivers |
ChromeDriver | Implements WebDriver methods |
By | Locator builder |
WebElement | Represents an element |
Select | For dropdowns |
📘 3. DOM (Document Object Model) and Selenium
🔹 What is the DOM?
The DOM is the structure of the web page represented as a tree of elements.
Selenium interacts with DOM via locators (id, xpath, cssSelector, etc.)
📖 Nepali View:
DOM भनेको page को HTML structure हो — Selenium ले यसैबाट element खोज्छ।
✅ Inspect using:
- Right click → Inspect
- DevTools (F12)
- Chrome Extension: ChroPath / SelectorsHub
🔹 Example DOM:
html
CopyEdit
<input type=”text” id=”username” name=”user”>
<button class=”loginBtn”>Login</button>
✅ Selenium Locator:
java
CopyEdit
driver.findElement(By.id(“username”)).sendKeys(“Lok”);
📘 4. pom.xml – The Maven Configuration File
🔹 What is pom.xml?
pom.xml (Project Object Model) is the core Maven file that contains:
- Project metadata
- Dependencies (like Selenium, TestNG)
- Plugins (compiler, surefire)
- Build configuration
🔸 pom.xml Sections Explained
xml
CopyEdit
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.yourproject</groupId> <!– Your base package –>
<artifactId>selenium-framework</artifactId> <!– Project name –>
<version>1.0-SNAPSHOT</version> <!– Current version –>
<dependencies>
<!– Selenium –>
<!– TestNG –>
<!– WebDriverManager –>
</dependencies>
<build>
<plugins>
<!– Compiler plugin –>
<!– Surefire plugin (for TestNG execution) –>
</plugins>
</build>
</project>
✅ Must-Have Dependencies
xml
CopyEdit
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.5.3</version>
</dependency>
🔸 Optional Build Plugins
xml
CopyEdit
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
📘 Selenium Topic 16: Advanced Framework Features
(Listeners, Retry, Logs, Reports, TDD vs BDD vs KDD, Cucumber)
🔹 1. TestNG Listeners
Listeners listen to the test execution and perform custom actions (logs, screenshots, etc.).
✅ Common Interface: ITestListener
Example:
java
CopyEdit
public class MyListener implements ITestListener {
public void onTestFailure(ITestResult result) {
System.out.println(“❌ Failed: ” + result.getName());
// Capture screenshot here
}
public void onTestSuccess(ITestResult result) {
System.out.println(“✅ Passed: ” + result.getName());
}
}
➡ Register via @Listeners or testng.xml
🔹 2. Retry Failed Tests
✅ Create Retry Class:
java
CopyEdit
public class RetryAnalyzer implements IRetryAnalyzer {
int count = 0;
int limit = 2;
public boolean retry(ITestResult result) {
if (count < limit) {
count++;
return true;
}
return false;
}
}
✅ Link in test method:
java
CopyEdit
@Test(retryAnalyzer = RetryAnalyzer.class)
public void flakyTest() {
// may pass/fail randomly
}
🔹 3. Logging (Log4j)
✅ Add Log4j dependency and use:
java
CopyEdit
Logger log = Logger.getLogger(“MyLogger”);
log.info(“Starting test”);
log.error(“Test failed due to XYZ”);
📌 Create a log4j.properties or log4j2.xml config.
🔹 4. Reporting
Tool | Use |
TestNG HTML report | Default /test-output/index.html |
Extent Reports | Beautiful HTML UI, screenshots |
Allure Reports | Dev-friendly, plugin-based |
Email Reports | Jenkins mail or custom mail API |

✅ Extent Report Example:
java
CopyEdit
ExtentReports extent = new ExtentReports();
ExtentTest test = extent.createTest(“Login Test”);
test.pass(“Logged in successfully”);
extent.flush();
📘 TDD vs BDD vs KDD
Model | Stands For | Driven By | Tools |
TDD | Test Driven Development | Unit tests first | JUnit, TestNG |
BDD | Behavior Driven Development | Scenario specs first | Cucumber, SpecFlow |
KDD | Keyword Driven Development | Keyword-action based | UFT, Selenium + Excel |
📖 Nepali View:
- TDD → code भन्दा पहिले test
- BDD → scenario लेखेर test
- KDD → keyword table बनाएर test चलाउने
📘 What is Cucumber?
Cucumber is a tool for BDD (Behavior Driven Development).
It uses Gherkin syntax (Given-When-Then) and integrates with Selenium + Java.
✅ Feature File:
gherkin
CopyEdit
Feature: Login Function
Scenario: Successful Login
Given User is on Login Page
When User enters username and password
Then Home page should be displayed
✅ Step Definitions:
java
CopyEdit
@Given(“User is on Login Page”)
public void userOnLoginPage() {
driver.get(“https://example.com/login”);
}
@When(“User enters username and password”)
public void enterCredentials() {
driver.findElement(By.id(“user”)).sendKeys(“Lok”);
}
✅ Tools:
- Cucumber JVM
- Gherkin
- JUnit or TestNG
✅ Ideal For:
- Business + QA collaboration
- English-like readable tests
- Traceable documentation + automation
📘 Selenium Topic 17: Cucumber Framework Setup (Step-by-Step with Maven + TestNG)
🔹 What is Cucumber Framework?
Cucumber is a BDD framework that lets you write automation scripts in natural English using the Gherkin language.
It bridges the gap between business logic and technical automation.
📖 Nepali Insight:
Cucumber ले तपाईंलाई test cases Given-When-Then को style मा लेख्न दिन्छ — जसले business + QA + dev को understanding एकैठाउँमा ल्याउँछ।
✅ Step-by-Step Cucumber Framework Setup (Maven + TestNG + Selenium)
🔸 1. Create Maven Project
In Eclipse or IntelliJ:
arduino
CopyEdit
File → New → Maven Project → Use archetype: maven-archetype-quickstart
🔸 2. Add Dependencies to pom.xml
xml
CopyEdit
<dependencies>
<!– Selenium –>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<!– Cucumber Java –>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-java</artifactId>
<version>7.11.2</version>
</dependency>
<!– Cucumber TestNG –>
<dependency>
<groupId>io.cucumber</groupId>
<artifactId>cucumber-testng</artifactId>
<version>7.11.2</version>
</dependency>
<!– TestNG –>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
</dependencies>
🔸 3. Create Folder Structure
vbnet
CopyEdit
src/
└── test/java/
├── features/ → .feature files (Gherkin steps)
├── stepDefinitions/ → Step definitions (Java logic)
├── runners/ → TestNG runner class
└── pages/ → Page Object Model classes
🔸 4. Create .feature File
📁 Location: features/Login.feature
gherkin
CopyEdit
Feature: Login Functionality
Scenario: Valid login
Given User is on Login Page
When User enters valid username and password
Then Home page should be displayed
🔸 5. Step Definitions (stepDefinitions/LoginSteps.java)
java
CopyEdit
public class LoginSteps {
WebDriver driver;
@Given(“User is on Login Page”)
public void user_is_on_login_page() {
driver = new ChromeDriver();
driver.get(“https://example.com/login”);
}
@When(“User enters valid username and password”)
public void enter_credentials() {
driver.findElement(By.id(“username”)).sendKeys(“Lok”);
driver.findElement(By.id(“password”)).sendKeys(“pass123”);
driver.findElement(By.id(“login”)).click();
}
@Then(“Home page should be displayed”)
public void home_page_should_be_displayed() {
Assert.assertEquals(driver.getTitle(), “Dashboard”);
driver.quit();
}
}
🔸 6. Runner Class (runners/TestRunner.java)
java
CopyEdit
@CucumberOptions(
features = “src/test/java/features”,
glue = “stepDefinitions”,
plugin = {“pretty”, “html:target/cucumber-reports”},
monochrome = true
)
@Test
public class TestRunner extends AbstractTestNGCucumberTests { }
✅ This integrates Cucumber with TestNG and generates HTML report.
🔸 7. Run the Test
📌 Run TestRunner.java as TestNG Test
📌 Reports auto-generate in target/cucumber-reports
✅ Bonus: Cucumber Tags for Selective Execution
In .feature file:
gherkin
CopyEdit
@smoke
Scenario: Valid login
In Runner:
java
CopyEdit
@CucumberOptions(
tags = “@smoke”
)
✅ Summary Table
File/Folder | Purpose |
pom.xml | Project dependencies |
.feature | Business-level test case |
Step Definitions | Actual Java code to implement feature |
Runner Class | Bridge between TestNG and Cucumber |
Reports | Auto-generated HTML |