Wednesday, 1 November 2017

Breakfast Conversation in German between Mother & Son

 

German Language Translation: Breakfast

Sohn: Mama, was gibt es heute zum Frühstück?
Mutter: Ich habe Brötchen, Marmelade, Käse und Eier vorbereitet. Was möchtest du?
Sohn: Kann ich ein Ei haben? Rührei, bitte!
Mutter: Natürlich, ich mache dir gleich eines. Möchtest du noch etwas dazu?
Sohn: Ja, vielleicht ein Brötchen mit Nutella.
Mutter: Okay, aber vergiss nicht, auch etwas Obst zu essen. Wie wäre es mit einem Apfel?
Sohn: Hm, vielleicht später. Ich habe jetzt Lust auf was Süßes.
Mutter: In Ordnung, aber denk dran, ein ausgewogenes Frühstück ist wichtig.


English Translation: Breakfast

Son: Mom, what’s for breakfast today?
Mother: I’ve prepared rolls, jam, cheese, and eggs. What would you like?
Son: Can I have an egg? Scrambled eggs, please!
Mother: Of course, I’ll make you one right away. Would you like anything else with it?
Son: Yes, maybe a roll with Nutella.
Mother: Okay, but don’t forget to eat some fruit too. How about an apple?
Son: Hmm, maybe later. I feel like having something sweet right now.
Mother: Alright, but remember, a balanced breakfast is important.

Thursday, 14 September 2017

How many SAAS Companies are there in the world?

 

SaaS (Software as a Service) is a cloud-based software delivery model where users access applications over the internet rather than installing them on their local computers or servers. SaaS providers host, manage, and update the software on their infrastructure, allowing users to subscribe to and use the software on a pay-as-you-go basis.

Key Features of SaaS:

  • Cloud-based: Hosted on remote servers and accessed via the internet.
  • Subscription Model: Users typically pay monthly or annually instead of buying a one-time license.
  • Automatic Updates: The provider handles maintenance, security, and updates.
  • Accessibility: Can be accessed from any device with an internet connection.
  • Scalability: Easily scalable based on user needs.

Examples of SaaS Software:

So SaaS is widely used by businesses and individuals due to its flexibility, cost-effectiveness, and ease of deployment.

As of 2024, there are approximately 30,800 Software as a Service (SaaS) companies operating globally. The United States leads with around 17,000 SaaS companies, accounting for about 60% of the global total. Other countries with significant numbers of SaaS companies include the United Kingdom with approximately 2,000, and Canada and Germany each hosting around 1,000. citeturn0search3

The SaaS industry has experienced rapid growth in recent years and is projected to continue expanding. Estimates suggest that the global SaaS market could reach a valuation of $700 billion by 2030, with a compound annual growth rate (CAGR) of 18.3% from 2022 to 2030. citeturn0search1

In terms of market share, no single company dominates the SaaS landscape. As of 2020, the five largest SaaS companies collectively held approximately 30.5% of the market. Salesforce leads with a market share of around 9.3%, followed closely by Microsoft at 8.7%. citeturn0search0

The SaaS sector is characterized by its dynamic nature, with frequent mergers, acquisitions, and new startups continually reshaping the market. This ongoing evolution contributes to the increasing number of SaaS companies worldwide.

 

Friday, 1 September 2017

Handling Dropdowns, Alerts and Frames in Selenium WebDriver

 


Introduction

Selenium WebDriver is widely used for automating web applications. During automation testing, testers frequently interact with dropdown menus, JavaScript alerts, confirmation boxes and frames.

These elements require specific Selenium commands because they behave differently from ordinary web elements.

For example, a standard HTML dropdown can be handled using Selenium's Select class, JavaScript alerts require the Alert interface, and frames require switching the WebDriver context.

In this tutorial, we will explore how to handle these common web elements using Selenium WebDriver with Java.

1. Handling Dropdowns in Selenium

Dropdowns are commonly used in registration forms, search filters, country selection and other web application features.

Selenium provides the Select class to interact with standard HTML select elements.

Example HTML Dropdown

<select id="country">
    <option value="india">India</option>
    <option value="usa">USA</option>
    <option value="uk">United Kingdom</option>
</select>

Import the Select Class

import org.openqa.selenium.support.ui.Select;

Create a Select Object

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

Select select =
    new Select(countryDropdown);

Select by Visible Text

select.selectByVisibleText("India");

This selects the option displaying the text "India".

Select by Value

select.selectByValue("usa");

This selects the option whose HTML value is usa.

Select by Index

select.selectByIndex(2);

The index is zero-based, so index 2 selects the third option.

Get the Selected Option

WebElement selectedOption =
    select.getFirstSelectedOption();

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

Get All Dropdown Options

List<WebElement> options = select.getOptions();

for (WebElement option : options) {
    System.out.println(option.getText());
}

Check Whether a Dropdown Supports Multiple Selection

if (select.isMultiple()) {
    System.out.println("Multiple selection is supported");
}

For a multi-select dropdown, you can select multiple options:

select.selectByVisibleText("India");
select.selectByVisibleText("USA");

You can deselect options using methods such as deselectAll() and deselectByVisibleText().

Important: The Selenium Select class works with standard HTML select elements. Custom dropdowns built using div, li or other HTML elements must generally be handled using ordinary locators and interactions.

2. Handling JavaScript Alerts in Selenium

JavaScript alerts are browser-generated dialog boxes that appear during certain webpage interactions.

Selenium provides the Alert interface to handle these dialogs.

There are three commonly encountered types.

A. Simple Alert

A simple alert displays a message and an OK button.

To accept the alert:

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

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

alert.accept();

The accept() method clicks the OK button.

B. Confirmation Alert

A confirmation alert generally provides OK and Cancel buttons.

To accept:

driver.switchTo().alert().accept();

To dismiss:

driver.switchTo().alert().dismiss();

The dismiss() method selects Cancel.

C. Prompt Alert

A prompt alert allows users to enter text.

Example:

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

alert.sendKeys("Palium Skills");

alert.accept();

This enters text into the prompt and accepts it.

Handling Alerts with Explicit Wait

Sometimes alerts appear after a delay. Selenium's WebDriverWait can wait until an alert is present.

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

Alert alert = wait.until(
    ExpectedConditions.alertIsPresent()
);

alert.accept();

Required imports include:

import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

This is generally more reliable than immediately switching to an alert that may not yet have appeared.

3. Handling Frames and Iframes in Selenium

A frame or iframe allows a webpage to display content from another document within the current page.

Selenium cannot directly interact with elements inside a frame while the driver remains in the main document context. You must switch into the frame first.

Example HTML

<iframe id="paymentFrame">
    <!-- Embedded page content -->
</iframe>

Switching to a Frame Using ID or Name

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

Switching Using Index

driver.switchTo().frame(0);

This selects the first frame in the current context. Index-based switching can be less maintainable if the page structure changes.

Switching Using WebElement

WebElement frameElement =
    driver.findElement(By.id("paymentFrame"));

driver.switchTo().frame(frameElement);

This approach is useful when the frame does not have a convenient ID or Name attribute.

Interacting with Elements Inside a Frame

After switching to the frame, locate and interact with its elements normally.

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

driver.findElement(By.id("cardNumber"))
      .sendKeys("123456789");

driver.switchTo().defaultContent();

The defaultContent() method returns WebDriver to the main page document.

Switching Between Nested Frames

Some applications contain frames inside other frames.

You must switch into the parent frame before accessing the nested frame.

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

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

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

driver.switchTo().defaultContent();

Switching to the Parent Frame

If you are inside a nested frame and want to return one level up, use:

driver.switchTo().parentFrame();

4. Complete Selenium Java Example

The following illustrative example demonstrates handling a dropdown and switching into a frame.

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class DropdownFrameExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        try {
            driver.manage().timeouts()
                  .implicitlyWait(Duration.ofSeconds(5));

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

            // Handle dropdown
            WebElement country =
                driver.findElement(By.id("country"));

            Select select = new Select(country);

            select.selectByVisibleText("India");

            // Switch to iframe
            driver.switchTo().frame("paymentFrame");

            driver.findElement(By.id("cardNumber"))
                  .sendKeys("123456789");

            // Return to main document
            driver.switchTo().defaultContent();

        } finally {
            driver.quit();
        }
    }
}

Replace the sample URL, frame name and element locators with those from your application.

5. Common Problems and Troubleshooting

ProblemPossible reasonSolution
Element not found inside iframeDriver is in the main documentSwitch to the correct frame
Alert not foundAlert has not appeared yetUse alertIsPresent() wait
Select class errorElement is not a standard selectHandle the custom dropdown using locators
Wrong dropdown option selectedIncorrect index or valueVerify option text, value and ordering
Unable to locate nested frameParent frame not selectedSwitch to the parent first

6. Best Practices

  • Identify whether a dropdown is a standard HTML select or a custom component.

  • Prefer visible text or stable option values over index selection.

  • Use explicit waits when alerts or frames appear dynamically.

  • Always switch back to the main document after completing frame interactions.

  • Verify alert messages before accepting or dismissing them.

  • Avoid mixing implicit and explicit waits unnecessarily because it can create unpredictable wait times.

Frequently Asked Questions

1. Which class is used to handle dropdowns in Selenium?

The Select class is used to handle standard HTML dropdown elements.

2. How do you handle JavaScript alerts in Selenium?

Use driver.switchTo().alert() and then call accept(), dismiss() or sendKeys() depending on the alert type.

3. What is the difference between a frame and an iframe?

Both allow embedded documents within a webpage. An iframe is an inline frame represented by the HTML iframe element.

4. How do you return from an iframe to the main webpage?

Use driver.switchTo().defaultContent() to return to the main document.

5. Can Selenium handle custom dropdowns using the Select class?

No. The Select class is designed for standard HTML select elements. Custom dropdowns generally require normal WebElement interactions.

Learn Selenium Automation Testing with Palium Skills

Palium Skills offers practical Selenium and Playwright automation testing training for freshers, manual testers and working professionals.

Training topics include:

  • Selenium WebDriver with Java and Python

  • Locators, XPath and CSS Selectors

  • Dropdowns, alerts, frames and browser handling

  • TestNG and PyTest automation frameworks

  • Page Object Model and framework development

  • API testing and real-time automation projects

  • Interview preparation and career guidance

Training modes: Classroom sessions at South Kolkata and Salt Lake centres, as well as instructor-led live online training for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Build practical automation testing skills with Palium Skills.

Saturday, 5 August 2017

10 Common Payroll Compliance Mistakes and How to Avoid Them

10 Common Payroll Compliance Mistakes and How to Avoid Them

 

Discover common payroll mistakes involving employee data, attendance, deductions, statutory compliance and payroll reporting.

 


 

Payroll mistakes can affect employees, HR teams and finance departments. Many errors can be reduced by creating clear processes, maintaining accurate data and performing regular payroll reviews.

1. Incorrect Employee Master Data

Incorrect bank details, joining dates, salary structures or statutory information can lead to payroll errors.

Solution: Regularly validate employee master data.

2. Incorrect Attendance Data

Missing attendance, incorrect leave information or unapproved adjustments can affect salary calculations.

Solution: Establish a clear attendance cut-off and approval process.

3. Incorrect Salary Structure

An incorrectly configured salary structure can affect earnings, deductions and reporting.

Solution: Review salary structures carefully before implementation.

4. Missing Payroll Inputs

Incentives, bonuses, overtime and reimbursements can sometimes be missed.

Solution: Use a monthly payroll input checklist.

5. Incorrect Statutory Calculations

Using outdated rules or incorrect employee information can create compliance issues.

Solution: Regularly verify current requirements and maintain documented payroll procedures.

6. Incorrect Professional Tax Rules

Professional Tax requirements can vary by state.

Solution: Apply the rules relevant to the employee's applicable state or jurisdiction.

7. Failure to Review Payroll Variances

Large changes in salary may indicate an error.

Solution: Compare the current payroll with previous periods.

8. Poor Record Management

Missing documentation can make audits and employee queries difficult.

Solution: Maintain organised payroll records.

9. Inadequate Data Security

Payroll data contains sensitive employee information.

Solution: Restrict access and follow appropriate data-security practices.

10. Lack of Payroll Knowledge

Payroll professionals who understand only data entry may struggle with complex calculations and employee queries.

Solution: Develop practical knowledge of payroll, Excel, compliance and HRMS.

Learn Practical Payroll with Palium Skills

Palium Skills helps learners build job-relevant skills through practical training and payroll projects.

Contact Palium Skills

South Kolkata: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar, Near South City Mall, Kolkata – 700068

Salt Lake: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091

Call: +91 8420594969 | WhatsApp: +91 9903130500
Email: info@paliumskills.com

Tuesday, 1 August 2017

Selenium Waits: Implicit, Explicit and Fluent Wait Explained with Examples

 

Introduction

One of the most common challenges in Selenium automation testing is dealing with web elements that do not appear immediately.

Modern websites frequently use JavaScript, AJAX requests, dynamic content loading and asynchronous operations. When an automation script tries to interact with an element before it becomes available, Selenium may throw exceptions such as NoSuchElementException or ElementNotInteractableException.

Selenium waits help solve this problem by allowing automation scripts to pause execution until a specified condition is satisfied or a maximum waiting time is reached.

There are three commonly discussed wait strategies in Selenium WebDriver:

  1. Implicit Wait

  2. Explicit Wait

  3. Fluent Wait

In this tutorial, we will understand each type with practical Java examples and learn when to use them.

1. What Are Waits in Selenium?

Waits are mechanisms that control how long Selenium waits for elements or conditions during test execution.

For example, consider a login page where the submit button appears only after a JavaScript operation finishes.

Without an appropriate wait, Selenium may try to click the button before it is available.

Waits help make automation scripts more reliable when dealing with dynamic webpages.

2. Implicit Wait in Selenium

Implicit Wait instructs WebDriver to wait for a specified duration when searching for elements that are not immediately available.

Once configured, it applies globally to element-location commands for that WebDriver instance.

Syntax

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

Complete Example

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class ImplicitWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

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

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

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

        } finally {
            driver.quit();
        }
    }
}

Advantages of Implicit Wait

  • Easy to configure.

  • Applies to element searches throughout the session.

  • Reduces immediate failures when elements take time to appear.

Limitations

  • It is not designed to wait for specific conditions such as an element becoming clickable.

  • It applies globally rather than to one particular element.

  • Combining implicit and explicit waits can produce unpredictable total wait times.

3. Explicit Wait in Selenium

Explicit Wait instructs Selenium to wait until a specific condition becomes true or a timeout occurs.

It is particularly useful for dynamic web applications where different elements may become available at different times.

Selenium provides WebDriverWait and ExpectedConditions to implement explicit waits.

Syntax

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

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

Common ExpectedConditions

Expected ConditionPurpose
visibilityOfElementLocated()Waits until an element is visible
elementToBeClickable()Waits until an element is visible and enabled
presenceOfElementLocated()Waits until an element exists in the DOM
alertIsPresent()Waits until a JavaScript alert appears
titleContains()Waits until the page title contains specified text
invisibilityOfElementLocated()Waits until an element becomes invisible or absent
textToBePresentInElementLocated()Waits until specified text appears

Example: Wait Until an Element Is Clickable

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

WebElement loginButton = wait.until(
    ExpectedConditions.elementToBeClickable(
        By.id("login")
    )
);

loginButton.click();

Example: Wait Until an Element Is Visible

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

username.sendKeys("admin");

Example: Wait for Text to Appear

wait.until(
    ExpectedConditions.textToBePresentInElementLocated(
        By.id("message"),
        "Login Successful"
    )
);

Explicit Wait is generally preferred when a test needs to wait for a particular condition rather than simply waiting for an element search.

4. Fluent Wait in Selenium

Fluent Wait is a configurable form of explicit waiting.

It allows testers to define:

  • Maximum waiting time.

  • Polling interval.

  • Exceptions to ignore while waiting.

For example, you can instruct Selenium to check a condition every two seconds for a maximum of twenty seconds.

Syntax

Wait<WebDriver> wait = new FluentWait<>(driver)
    .withTimeout(Duration.ofSeconds(20))
    .pollingEvery(Duration.ofSeconds(2))
    .ignoring(NoSuchElementException.class);

Complete Java Example

import java.time.Duration;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;

public class FluentWaitExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

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

            Wait<WebDriver> wait = new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(20))
                .pollingEvery(Duration.ofSeconds(2))
                .ignoring(NoSuchElementException.class);

            WebElement element = wait.until(
                d -> d.findElement(By.id("username"))
            );

            element.sendKeys("testuser");

        } finally {
            driver.quit();
        }
    }
}

The example repeatedly searches for the username field until it is found or the timeout expires.

Advantages of Fluent Wait

  • Custom polling intervals.

  • Configurable timeout.

  • Ability to ignore selected exceptions.

  • Useful for elements that appear unpredictably.

5. Difference Between Implicit, Explicit and Fluent Wait

FeatureImplicit WaitExplicit WaitFluent Wait
ScopeGlobal element searchesSpecific conditionSpecific condition
ConfigurationSimple timeoutTimeout and conditionTimeout, polling and ignored exceptions
Polling controlNoLimited/default polling configurationYes
Expected conditionsNoYesCan use custom conditions
Best suited forGeneral element searchesDynamic elements and conditionsSpecial cases needing custom polling

Which one should you use?

For most modern Selenium automation projects, explicit waits are a practical default. Fluent Wait is useful when custom polling and exception handling are required. Implicit Wait may be used for simpler element-search scenarios, but avoid combining it with explicit waits in the same test suite.

6. Common Selenium Wait Exceptions

Understanding common exceptions helps automation testers troubleshoot failures.

NoSuchElementException: Selenium cannot find the element using the supplied locator.

TimeoutException: The expected condition was not satisfied within the configured timeout.

StaleElementReferenceException: The element reference is no longer attached to the current DOM, often because the page has changed or refreshed.

ElementNotInteractableException: The element exists but cannot be interacted with in its current state.

In some cases, the correct solution is to wait for the element to become visible, enabled or clickable. For stale elements, it may be necessary to locate the element again after the DOM changes.

7. Best Practices for Selenium Waits

  1. Prefer condition-based explicit waits for dynamic elements.

  2. Avoid using Thread.sleep() as the default waiting strategy.

  3. Do not mix implicit and explicit waits unnecessarily.

  4. Use appropriate ExpectedConditions.

  5. Choose realistic timeout values based on application behaviour.

  6. Re-locate elements when the DOM changes and references become stale.

  7. Use reusable wait methods in automation frameworks.

  8. Avoid waiting for clickability when the actual requirement is only element presence or visibility.

8. Creating a Reusable Explicit Wait Method

In a professional automation framework, wait logic can be placed in a reusable utility class.

public WebElement waitForElement(By locator) {

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

    return wait.until(
        ExpectedConditions.visibilityOfElementLocated(locator)
    );
}

This method can be reused across multiple test classes and Page Object Model components.

Frequently Asked Questions

1. What are the three types of waits in Selenium?

The commonly used types are Implicit Wait, Explicit Wait and Fluent Wait.

2. Which wait is best in Selenium?

Explicit Wait is generally a good choice because it waits for a specific condition rather than applying a global delay.

3. What is the difference between Explicit Wait and Fluent Wait?

Fluent Wait provides additional control over polling intervals and ignored exceptions. Both are condition-based waiting approaches.

4. Why should Thread.sleep() be avoided?

It pauses execution for a fixed duration regardless of whether the element is already available. This can make tests slower and less efficient.

5. Can implicit and explicit waits be used together?

Although Selenium permits both, combining them can lead to unpredictable waiting times. It is generally better to use explicit waits consistently for condition-based synchronisation.

Learn Selenium Automation Testing with Palium Skills

Palium Skills provides practical automation testing training for freshers, manual testers and working professionals.

The Selenium and Playwright training curriculum can include:

  • Selenium WebDriver with Java and Python

  • Implicit, Explicit and Fluent Wait

  • XPath and CSS Selector

  • TestNG and PyTest

  • Page Object Model and automation framework development

  • API testing and real-time projects

  • Interview preparation and career guidance

Training modes: Classroom sessions at South Kolkata and Salt Lake centres, plus instructor-led live online training for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Build your automation testing expertise with practical training from Palium Skills.

Saturday, 1 July 2017

Selenium TestNG Framework Tutorial: Annotations, Assertions and Test Execution

 


Introduction

Selenium WebDriver is a popular tool for automating web applications. However, Selenium alone does not provide a complete test management framework for organising, executing and reporting automated test cases.

This is where TestNG becomes useful.

TestNG is a Java testing framework inspired by JUnit and NUnit. It provides features such as annotations, assertions, test prioritisation, grouping, parameterisation, dependencies and parallel execution.

When combined with Selenium WebDriver, TestNG helps automation testers build structured, maintainable and reusable test automation suites.

In this tutorial, we will understand TestNG concepts and learn how to integrate TestNG with Selenium using practical Java examples.

1. What Is TestNG?

TestNG stands for Test Next Generation. It is a testing framework designed to simplify test organisation and execution.

It is commonly used in Selenium automation projects to:

  • Organise test cases.

  • Control test execution order.

  • Run tests in groups.

  • Validate expected and actual results.

  • Execute tests with different data sets.

  • Support parallel execution.

  • Generate execution reports.

TestNG is particularly useful when developing a Selenium automation framework for a real-world application.

2. Installing TestNG in a Selenium Java Project

You can use TestNG with Eclipse and Maven.

Step 1: Create a Maven Project

Open Eclipse and create a new Maven project.

Step 2: Add Dependencies

Add Selenium and TestNG dependencies to your pom.xml file.

<dependencies>

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

    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.11.0</version>
        <scope>test</scope>
    </dependency>

</dependencies>

These are example dependency versions. Use compatible current versions when setting up a new project.

Step 3: Install the TestNG Eclipse Plugin

In Eclipse:

  1. Open the Eclipse Marketplace.

  2. Search for TestNG.

  3. Install the TestNG plugin.

  4. Restart Eclipse if prompted.

You can also execute TestNG tests through Maven without relying on the Eclipse plugin.

3. Understanding TestNG Annotations

Annotations are one of the most important features of TestNG. They control when different test methods and configuration methods execute.

Common TestNG annotations include:

AnnotationPurpose
@BeforeSuiteRuns before the test suite
@AfterSuiteRuns after the test suite
@BeforeTestRuns before the relevant XML test
@AfterTestRuns after the relevant XML test
@BeforeClassRuns before the first test method in a class
@AfterClassRuns after all test methods in a class
@BeforeMethodRuns before each test method
@AfterMethodRuns after each test method
@TestMarks a test method

Example of TestNG Annotations

import org.testng.annotations.*;

public class AnnotationExample {

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

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

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

    @Test
    public void testLogin() {
        System.out.println("Executing Login Test");
    }

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

    @AfterClass
    public void afterClass() {
        System.out.println("After Class");
    }

    @AfterSuite
    public void afterSuite() {
        System.out.println("After Suite");
    }
}

The annotations help testers control test setup, execution and cleanup.

4. Writing a Selenium TestNG Test Case

Let us create a simple Selenium test that opens a webpage and verifies its title.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.*;

public class SeleniumTestNGExample {

    WebDriver driver;

    @BeforeMethod
    public void setUp() {
        driver = new ChromeDriver();
        driver.get("https://example.com");
    }

    @Test
    public void verifyPageTitle() {

        String actualTitle = driver.getTitle();

        Assert.assertEquals(
            actualTitle,
            "Example Domain"
        );
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() {

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

In this example:

  • @BeforeMethod launches the browser and opens the webpage.

  • @Test executes the validation.

  • Assert.assertEquals() compares the actual and expected page titles.

  • @AfterMethod closes the browser even if the test fails.

5. TestNG Assertions

Assertions are used to verify whether an application behaves as expected.

TestNG provides several assertion methods.

Assert Equals

Assert.assertEquals(actual, expected);

Checks whether two values are equal.

Assert True

Assert.assertTrue(driver.getTitle().contains("Example"));

Checks whether a condition is true.

Assert False

Assert.assertFalse(driver.getTitle().contains("Error"));

Checks whether a condition is false.

Assert Not Null

Assert.assertNotNull(driver);

Checks whether an object is not null.

Hard Assertions and Soft Assertions

A hard assertion stops the current test method when an assertion fails.

Soft assertions allow execution to continue after an assertion failure. The tester must call assertAll() to report accumulated failures.

import org.testng.asserts.SoftAssert;

SoftAssert softAssert = new SoftAssert();

softAssert.assertEquals(actualTitle, expectedTitle);
softAssert.assertTrue(driver.getCurrentUrl().contains("example"));

softAssert.assertAll();

6. TestNG Priority

TestNG allows test methods to be assigned priorities.

@Test(priority = 1)
public void loginTest() {
    System.out.println("Login Test");
}

@Test(priority = 2)
public void dashboardTest() {
    System.out.println("Dashboard Test");
}

@Test(priority = 3)
public void logoutTest() {
    System.out.println("Logout Test");
}

Lower numeric priorities execute before higher numeric priorities under normal TestNG execution.

However, priority should not be used as a substitute for proper test independence or dependency management.

7. TestNG Groups

Groups allow related test cases to be organised and executed together.

@Test(groups = {"smoke"})
public void loginTest() {
    System.out.println("Smoke Test");
}

@Test(groups = {"regression"})
public void paymentTest() {
    System.out.println("Regression Test");
}

You can select groups for execution through a TestNG XML configuration file.

8. TestNG XML Configuration

A TestNG XML file helps control which test classes, methods or groups should execute.

Example testng.xml:

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">

<suite name="AutomationSuite">

    <test name="LoginTests">

        <classes>
            <class name="SeleniumTestNGExample"/>
        </classes>

    </test>

</suite>

You can run this configuration as a TestNG Suite from Eclipse or through a compatible Maven TestNG setup.

9. TestNG Parameterisation

Parameterisation allows the same test method to execute with different input values.

TestNG supports parameters through @Parameters and data-driven execution through @DataProvider.

Using DataProvider

@DataProvider(name = "loginData")
public Object[][] getLoginData() {

    return new Object[][] {
        {"user1", "pass1"},
        {"user2", "pass2"},
        {"user3", "pass3"}
    };
}

@Test(dataProvider = "loginData")
public void loginTest(String username, String password) {

    System.out.println(username);
    System.out.println(password);
}

This approach is useful for testing login functionality with multiple combinations of credentials.

10. Parallel Execution in TestNG

TestNG supports parallel execution through XML configuration.

Example:

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

    <test name="AutomationTests">
        <classes>
            <class name="SeleniumTestNGExample"/>
        </classes>
    </test>

</suite>

Parallel execution can reduce overall test duration. However, Selenium tests must use properly isolated WebDriver instances, commonly through ThreadLocal or another safe driver-management approach, to avoid browser-session conflicts.

11. TestNG Reports

TestNG generates execution reports after running tests.

Common output files include:

  • test-output/index.html

  • test-output/emailable-report.html

These reports help testers review:

  • Passed test cases.

  • Failed test cases.

  • Skipped tests.

  • Execution details.

  • Error information.

For larger automation projects, TestNG reports can also be integrated with reporting tools such as Allure or Extent Reports.

12. Best Practices for Selenium TestNG Frameworks

  1. Keep test methods focused on one validation objective.

  2. Use meaningful test method names.

  3. Separate browser setup and cleanup from test logic.

  4. Use assertions to validate actual application behaviour.

  5. Use DataProviders for multiple test inputs.

  6. Organise smoke and regression tests into groups.

  7. Avoid unnecessary dependencies between test cases.

  8. Use isolated WebDriver instances for parallel execution.

  9. Maintain reusable methods and Page Object Model classes.

  10. Integrate automated execution with CI/CD pipelines.

Frequently Asked Questions

1. What is TestNG in Selenium?

TestNG is a Java testing framework used with Selenium WebDriver to organise, execute and report automated test cases.

2. What are the most important TestNG annotations?

Common annotations include @Test, @BeforeMethod, @AfterMethod, @BeforeClass, @AfterClass, @BeforeSuite and @AfterSuite.

3. What is the difference between hard and soft assertions?

Hard assertions stop the current test method after a failure. Soft assertions collect failures and report them when assertAll() is called.

4. What is DataProvider in TestNG?

@DataProvider supplies multiple sets of test data to a test method.

5. Can TestNG execute Selenium tests in parallel?

Yes. TestNG supports parallel execution at suite, test, class and method levels, provided the automation framework manages browser sessions safely.

6. Is TestNG required for Selenium?

No. Selenium can be used with other test frameworks, but TestNG is a popular choice for Java-based automation projects.

Learn Selenium Automation Testing with Palium Skills

Palium Skills provides practical automation testing training for freshers, manual testers and working professionals.

The Selenium and Playwright training curriculum can include:

  • Selenium WebDriver with Java and Python.

  • TestNG annotations, assertions and DataProviders.

  • XPath and CSS Selector techniques.

  • Page Object Model and automation framework development.

  • API testing and integration.

  • Maven, Git and Jenkins.

  • Real-time automation projects.

  • Interview preparation and career guidance.

Training modes: Classroom sessions at South Kolkata and Salt Lake centres, and instructor-led live online training for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Build practical Selenium automation and software testing skills with Palium Skills through classroom and live online training.

Thursday, 1 June 2017

Page Object Model (POM) in Selenium: Complete Guide with Java Examples

 



As Selenium automation projects grow, maintaining test scripts becomes increasingly challenging. A simple automation script may work well for a few test cases, but larger applications can have hundreds of pages, elements and workflows.

If element locators and test logic are repeated across multiple scripts, even a small change in the application can require updates in several places.

The Page Object Model (POM) is a popular design pattern used in Selenium automation testing to solve this problem.

POM separates webpage-specific elements and interactions from test execution logic. This makes automation frameworks easier to maintain, reuse and expand.

In this tutorial, we will understand the Page Object Model, its advantages, project structure and implementation using Selenium WebDriver with Java and TestNG.

1. What Is Page Object Model in Selenium?

Page Object Model is a design pattern in which each application page or meaningful page component is represented by a separate Java class.

Each page class generally contains:

  • Web element locators.

  • Methods to interact with those elements.

  • Page-specific operations.

  • Reusable functionality.

For example, an e-commerce application may contain:

  • Login Page

  • Home Page

  • Product Page

  • Shopping Cart Page

  • Checkout Page

Each of these can be represented by a separate Java class.

Instead of writing the same element locators repeatedly in test cases, testers maintain them in their corresponding page classes.

2. Why Is Page Object Model Required?

Consider a login page containing username, password and login button elements.

Without POM, the same locators may be repeated in several test scripts.

If the username field's ID changes, multiple test cases may need modification.

With POM, the locator is maintained in one page class. Updating it there can benefit every test that uses that class.

Advantages of POM

  1. Maintainability: Element locators are organised centrally.

  2. Reusability: Page methods can be reused across test cases.

  3. Readability: Test scripts become easier to understand.

  4. Scalability: New pages and workflows can be added systematically.

  5. Reduced duplication: Common page interactions do not need to be repeated.

  6. Separation of responsibilities: Page interactions are separated from test execution and validation.

3. Typical Selenium POM Framework Structure

A Maven-based Selenium automation project may use the following structure:

SeleniumAutomationFramework
│
├── src/main/java
│   ├── pages
│   │   ├── LoginPage.java
│   │   ├── HomePage.java
│   │   └── ProductPage.java
│   │
│   └── utilities
│       └── DriverFactory.java
│
├── src/test/java
│   ├── tests
│   │   ├── LoginTest.java
│   │   └── ProductTest.java
│   │
│   └── base
│       └── BaseTest.java
│
├── pom.xml
└── testng.xml

The exact folder structure may vary depending on project requirements.

4. Creating a Login Page Class

Let us create a simple Login Page using Selenium WebDriver.

LoginPage.java

package pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class LoginPage {

    WebDriver driver;

    By username =
        By.id("username");

    By password =
        By.id("password");

    By loginButton =
        By.id("login");

    public LoginPage(WebDriver driver) {
        this.driver = driver;
    }

    public void enterUsername(String user) {
        driver.findElement(username).sendKeys(user);
    }

    public void enterPassword(String pass) {
        driver.findElement(password).sendKeys(pass);
    }

    public void clickLogin() {
        driver.findElement(loginButton).click();
    }

    public void login(String user, String pass) {
        enterUsername(user);
        enterPassword(pass);
        clickLogin();
    }
}

This class contains the locators and operations required to interact with the login page.

The constructor receives the WebDriver instance so that the page object uses the browser session managed by the test framework.

5. Creating a Base Test Class

A Base Test class can manage common browser setup and cleanup.

BaseTest.java

package base;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;

public class BaseTest {

    protected WebDriver driver;

    @BeforeMethod
    public void setUp() {

        driver = new ChromeDriver();

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

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

    @AfterMethod(alwaysRun = true)
    public void tearDown() {

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

This example creates a fresh browser session before each test method and closes it afterward.

For larger projects, browser creation can be moved into a reusable Driver Factory.

6. Creating a Login Test Using POM

Now we can use the LoginPage class in a TestNG test.

LoginTest.java

package tests;

import base.BaseTest;
import pages.LoginPage;

import org.testng.Assert;
import org.testng.annotations.Test;

public class LoginTest extends BaseTest {

    @Test
    public void verifySuccessfulLogin() {

        LoginPage loginPage =
            new LoginPage(driver);

        loginPage.login(
            "testuser",
            "Test@123"
        );

        Assert.assertTrue(
            driver.getCurrentUrl().contains("dashboard")
        );
    }
}

The test method does not need to know how the username field or login button is located.

It simply calls the page method and validates the result.

The URL and element locators are illustrative; they should be replaced with those of the application under test.

7. What Is Page Factory in Selenium?

Page Factory is a Selenium support feature that provides a convenient way to initialise page elements using annotations such as @FindBy.

Example:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {

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

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

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

    public LoginPage(WebDriver driver) {

        PageFactory.initElements(driver, this);
    }

    public void login(String user, String pass) {

        username.sendKeys(user);
        password.sendKeys(pass);
        loginButton.click();
    }
}

Page Factory is optional. A POM framework can also use ordinary By locators and findElement() calls.

Modern Selenium frameworks often prefer explicit locator management because it makes element lookup and wait behaviour easier to control.

8. Difference Between POM and Page Factory

FeaturePage Object ModelPage Factory
TypeDesign patternSelenium support feature
PurposeOrganises page-specific codeInitialises page elements
Element definitionCommonly uses By locatorsCommonly uses @FindBy
RequirementCan be implemented without Page FactoryUsed within a page-object design
FlexibilityHighProvides a convenient annotation-based approach

Page Factory does not replace POM. It is one optional way of implementing page objects.

9. Best Practices for Building a POM Framework

  • Maintain separate page classes for application pages or components.

  • Keep locators and page interactions inside page classes.

  • Keep assertions and test scenarios primarily in test classes.

  • Use meaningful method and class names.

  • Avoid duplicating browser setup across test classes.

  • Use explicit waits for dynamic elements.

  • Maintain reusable utility methods carefully.

  • Keep test data separate from test logic.

  • Use Maven for dependency management.

  • Integrate the framework with Git and CI/CD tools.

10. Common POM Interview Questions

1. What is Page Object Model in Selenium?

POM is a design pattern that represents application pages or components as separate classes containing locators and interaction methods.

2. What are the benefits of POM?

It improves maintainability, reusability, readability and scalability while reducing duplicated code.

3. Is Page Factory mandatory for POM?

No. Page Factory is optional. POM can be implemented using standard Selenium locators and WebDriver methods.

4. Where should assertions be written in a POM framework?

Assertions are generally placed in test classes so that page objects focus on page interactions and the tests focus on validation.

5. Can POM be used with TestNG?

Yes. POM is commonly combined with TestNG to organise page interactions and manage test execution.

6. Can POM be used with Selenium Python?

Yes. The Page Object Model is a design pattern and can be implemented in Python using Selenium and frameworks such as PyTest.

Learn Selenium Automation Framework Development with Palium Skills

Learning Selenium commands is only the first step toward becoming an automation test engineer. Developing a reusable automation framework is an important practical skill.

Palium Skills offers Selenium and Playwright automation testing training covering:

  • Selenium WebDriver with Java and Python.

  • Page Object Model and framework development.

  • TestNG and PyTest.

  • XPath and CSS Selector.

  • Data-driven automation testing.

  • API testing and integration.

  • Maven, Git and Jenkins.

  • Real-time automation projects.

  • Interview preparation and career guidance.

Training modes: Classroom training at South Kolkata and Salt Lake centres, plus instructor-led live online sessions for learners across India.

Contact Palium Skills

South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.

Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.

Build practical Selenium automation frameworks with Palium Skills through classroom and live online training.

TDS on Salary: A Practical Guide for HR and Payroll Professionals

  TDS on Salary: A Complete Guide for HR and Payroll Professionals Learn how TDS on salary works in India , the role of employers, employee...