Selenium

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

FeatureDescription
Open SourceFree and widely supported
Browser SupportChrome, Firefox, Edge, Safari
Language SupportJava, Python, C#, JS, Ruby
Framework IntegrationTestNG, JUnit, Maven, Jenkins
Cross-platformRun on Windows, Mac, Linux
Parallel ExecutionWith Selenium Grid

🔹 Components of Selenium Suite

ComponentPurpose
Selenium WebDriverAutomates browser actions
Selenium IDERecord-playback browser extension
Selenium GridRun 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)

ToolPurpose
JavaProgramming language
Eclipse or IntelliJIDE for writing code
MavenDependency & project management
Selenium WebDriverCore automation tool
ChromeDriver / GeckoDriverBrowser-specific drivers
TestNG or JUnitTest execution framework
BrowserChrome, 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

LayerDescription
Test ScriptJava code written by QA to automate tests
Selenium WebDriver APIProvides commands (click, sendKeys, get)
Browser-Specific DriverConverts API commands to browser-specific actions
Real BrowserBrowser like Chrome/Firefox where test runs

🔹 Flow Explained Step-by-Step

  1. Test script sends command: driver.get(“https://gainsco.com”)
  2. WebDriver API translates it into HTTP request
  3. ChromeDriver.exe / geckodriver.exe receives the request
  4. ✅ Browser Driver uses JSON Wire Protocol / W3C Protocol to send commands to the browser
  5. Browser executes the action (open URL, click, enter text)
  6. ✅ Response comes back the same way

📖 Nepali Flow:
तपाईंले लेखेको code → WebDriver ले समझ्यो → Driver ले browser लाई command पठायो → browser ले काम गर्‍यो → result फर्कायो।


🔹 Browser Drivers and Their Role

BrowserDriverDownload Location
ChromeChromeDriverchromedriver.chromium.org
FirefoxGeckoDrivergithub.com/mozilla/geckodriver
EdgeEdgeDriverMicrosoft Edge site
SafariBuilt-in SafariDrivermacOS only

📌 All drivers must match the browser version and be in system path or project folder.


🔹 WebDriver Communication Protocols

ProtocolDescription
JSON Wire ProtocolUsed in older Selenium versions
W3C WebDriver ProtocolUsed 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

ComponentRole
Test ScriptJava code you write
WebDriver APIMiddle layer
Browser DriverConverts API to browser-level commands
BrowserExecutes the actions (UI)
ProtocolJSON Wire or W3C (communication format)

📘 Selenium Topic 3: Setting Up a Selenium Project (Maven, Dependencies, Folder Structure)


🔹 Tools Needed

ToolPurpose
Java (JDK 8 or above)Core language
Eclipse / IntelliJIDE for writing code
MavenBuild & dependency manager
ChromeDriverBrowser driver
Selenium WebDriverAutomation API
TestNG or JUnitTest 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

StepTask
1Create Maven project
2Add Selenium + TestNG dependencies in pom.xml
3Set up ChromeDriver
4Write test in src/test/java
5Run 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 TypeMethodUsage
idBy.id(“value”)Fastest and preferred
nameBy.name(“value”)Often used for forms
classNameBy.className(“value”)When class is unique
tagNameBy.tagName(“input”)Less used
linkTextBy.linkText(“Exact Text”)Full visible link text
partialLinkTextBy.partialLinkText(“Part”)Partial match
cssSelectorBy.cssSelector(“pattern”)Fast, powerful
xpathBy.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?

LocatorUse When
idAlways use first if available
nameNext best for inputs
cssSelectorFast, flexible
xpathComplex DOM, dynamic data
linkTextFor full visible links
classNameIf unique & single class

✅ Summary Table

LocatorSyntaxUse Case
idBy.id(“id”)Fastest, unique
nameBy.name(“name”)Forms
classNameBy.className(“value”)Single class
cssSelectorBy.cssSelector(“pattern”)Fast + readable
xpathBy.xpath(“//tag[@attr=’val’]”)Most powerful
linkTextBy.linkText(“Full Text”)Full clickable links
partialLinkTextBy.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

TypeSyntaxExample
Absolute/html/body/div[1]/input❌ Avoid
Relative//tag[@attr=’value’]✅ //input[@id=’email’]

✅ Common XPath Functions

FunctionUseExample
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.

AxisDescriptionExample
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

TipDescription
Use contains()For dynamic attribute values
Use starts-with()If prefix is fixed
Prefer text()For clickable links/buttons
Avoid absolute pathsThey break easily
Use AxesFor table-based or nested elements

✅ Summary Table

TopicExampleUse
text()//h2[text()=’Welcome’]Exact match
contains()//a[contains(text(),’Login’)]Partial
axesfollowing-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

ElementAction
DropdownSelect class (selectByText/Index/Value)
CheckboxisSelected(), then click()
RadioSame as checkbox
Linkclick(), getText()
iFrameswitchTo().frame(), defaultContent()
New Window/TabgetWindowHandles(), switchTo().window()
PaginationLoop + click Next
ScrollJavascriptExecutor
TooltipgetAttribute(“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

TypeApplied OnDescription
Implicit WaitGloballyWaits for a fixed time before failing
Explicit WaitFor specific elementsWaits until condition is true
Fluent WaitLike explicit + pollingAdvanced 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 CaseWait Type
General UI loadImplicit
Specific AJAX callExplicit
Retry with pollingFluent

🧠 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

WaitScopeFlexibilityExample
ImplicitGlobal❌ Fixed timeimplicitlyWait(10)
ExplicitPer element✅ Condition-basedWebDriverWait + ExpectedConditions
FluentPer element✅ + pollingFluentWait().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

TypeAction
Simple Alertalert.accept();
Confirmation Alertalert.dismiss(); or accept();
Prompt Alertalert.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

TaskTechnique
AlertswitchTo().alert().accept()
Confirmalert.dismiss()
Promptalert.sendKeys()
Modal PopupfindElement().click()
Upload FilesendKeys(“path”) to input element
Download FileUse 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?

BenefitDescription
Structured testingUse @Test, @BeforeMethod, @AfterMethod
Grouping & prioritizingControl which tests to run
Parallel executionRun tests faster
Report generationAutomatic HTML reports
Flexible configurationtestng.xml for setup

🔸 1. TestNG Annotations

AnnotationPurpose
@TestMarks a method as a test
@BeforeSuiteRuns once before all tests in the suite
@BeforeTestRuns before <test> tag in XML
@BeforeClassRuns once before first method in class
@BeforeMethodRuns before each @Test method
@AfterMethodRuns after each @Test method
@AfterClassRuns once after last test in class
@AfterSuiteRuns 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

AnnotationWherePurpose
@ParametersTest methodInject data from XML
@DataProviderFor DDTReturn test data in array
dependsOnMethodsTest chainingRun test only if another passes
enabled=falseAny testSkip test temporarily

✅ Summary Table

FeatureSyntaxUse
Mark test@TestAny method
Setup/teardown@BeforeMethod, @AfterMethodWebDriver open/close
Group tests@Test(groups=”smoke”)Run selected tests
Prioritize@Test(priority=1)Control test order
XML configtestng.xmlManage 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

SourceHow to UseBest For
@DataProviderJava method returning Object[][]Simple inline test data
@Parameters + XMLtestng.xml valuesConfig-based test inputs
ExcelApache POILarge test data sheets
JSONJSON.simple, JacksonAPI testing, configs
CSV/TXTJava IOLightweight input files

🧪 QA Usage Examples

Use CaseTechnique
Login forms with 10 usersDataProvider
Browser/environment@Parameters from XML
Complex insurance dataExcel-driven POI
API payload valuesJSON 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

BenefitDescription
ReusabilityReuse locators/methods across tests
MaintainabilityUpdate only in one place if UI changes
ReadabilityCode looks like natural language (e.g., loginPage.login())
ScalabilityEasy 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

ComponentLocationRole
TestBase.javabase/Driver setup & teardown
LoginPage.javapages/Page fields and actions
LoginTest.javatests/Test case logic
pom.xmlrootDependencies

🧪 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)

TermStops test?Used when
AssertYesCritical failure
SoftAssertNoOptional checks
Verify (custom)NoLog 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

FeatureClass/ToolUsage
Hard AssertionAssertStops test on failure
Soft AssertionSoftAssertLogs all failures after .assertAll()
LogsSystem.out.println() / Reporter.log()Debug/test progress
Reporttest-output/index.htmlHTML result summary
Advanced ReportExtent, AllureBeautiful 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?

ReasonBenefit
Browser compatibilityEnsure UI and functionality behave the same
Real-world coverageSimulates how different users access your site
Bug identificationCatch browser-specific bugs early

✅ Required Setup

BrowserDriver Required
ChromeChromeDriver
FirefoxGeckoDriver
EdgeEdgeDriver

📌 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

TipDescription
Use WebDriverManagerAuto-manages driver versions
Avoid browser-specific XPathUse CSS or stable attributes
Add waitsHandle rendering speed differences
Run in headless modeFor 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

FeatureTool/Code
Multi-browser supporttestng.xml with <parameter name=”browser”/>
Driver logicif-else or switch-case in setup method
Parallel execution<suite parallel=”tests”>
Auto driver handlingWebDriverManager
Supported browsersChrome, 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>

OptionMeaning
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

ComponentRole
HubCentral controller
NodeExecutes test on a machine/browser

🔸 Step-by-Step for Grid (Selenium 4)

✅ Start Selenium Grid Hub & Node (Local)

  1. Download Selenium Standalone Server or run via Docker
  2. 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

TipDescription
Use thread-safe driverDon’t reuse same WebDriver across threads
Manage drivers carefullyClose after each method
Scale nodes for real load1 node per browser version
Use ExtentReport or AllureMerge reports after parallel runs

✅ Summary Table

TechniqueTools
Parallel in same machinetestng.xml + thread-count
Cross-machine executionSelenium Grid
Parallel methodsparallel=”methods”
Parallel browsersNodes with Chrome, Firefox, etc.
Thread safetyUse 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:

  1. Install Jenkins
  2. Create a new job (freestyle or Maven)
  3. Source Code Management → GitHub Repo
  4. Build → mvn clean test
  5. 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

ToolPurpose
ExtentReports / AllureBetter visual reporting
Log4jLogging
RestAssuredAPI test integration
Docker + GridScalable browser execution
GitHub ActionsCloud CI/CD

✅ Summary Table

ComponentRole
MavenProject build & dependency manager
POMCode organization (pages, base, tests)
TestNGTest control & reporting
DDTExcel, JSON, DataProvider
JenkinsContinuous test execution
OptionalReports, Logging, CI tools

📘 1. Java OOPs Concepts in Page Object Model (POM)


🔹 🔸 OOPs Concept → Where It Appears in Selenium Framework

OOP ConceptExample in POM Framework
EncapsulationPage classes have private By locators + public methods to access them
InheritanceTest classes extend TestBase for setup/teardown
PolymorphismMethod clickLogin() works differently in AdminPage vs UserPage
AbstractionPages 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

ClassUse
WebDriverInterface for all browser drivers
ChromeDriverImplements WebDriver methods
ByLocator builder
WebElementRepresents an element
SelectFor 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

ToolUse
TestNG HTML reportDefault /test-output/index.html
Extent ReportsBeautiful HTML UI, screenshots
Allure ReportsDev-friendly, plugin-based
Email ReportsJenkins mail or custom mail API
Generated image

✅ 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

ModelStands ForDriven ByTools
TDDTest Driven DevelopmentUnit tests firstJUnit, TestNG
BDDBehavior Driven DevelopmentScenario specs firstCucumber, SpecFlow
KDDKeyword Driven DevelopmentKeyword-action basedUFT, 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/FolderPurpose
pom.xmlProject dependencies
.featureBusiness-level test case
Step DefinitionsActual Java code to implement feature
Runner ClassBridge between TestNG and Cucumber
ReportsAuto-generated HTML
Scroll to Top