Saturday, 9 December 2017

Standing upto Bosses



We receive numerous forward messages on Whatsapp and email. Most of them can be ignored but once in a while one receives a message which sets you thinking. Here is one such article which struck a chord within me and left me admiring Mr. R. K. Talwar.
Frankly, I had not heard about him before this message. Hence, it is being shared as it shows what a fine example of Chairman he was - standing up for his conviction and also standing upto his political bosses. We hardly hear of such people these days ... Read on
*The Talwar Amendment*
by Mr. N. Vaghul
R.K. Talwar was a highly respected banker who was the Chairman of State Bank of India from 1959 to 1974. He was removed from his office for his principled stand against an unjust and unethical interference by the Government in the functioning of the Bank. The government had to amend the laws in the parliament in order to get rid of Talwar, which became well known in banking circles as the "Talwar Amendment." In this article, a close confidant of Talwar describes the episode, which can be an inspiring example of professional courage to young people.
There was no doubt whatsoever that the Amendment was introduced with a single purpose of removing Talwar from the office of the Chairman, even though the bill was clothed in general terms and included several other provisions which were not quite significant. What did Talwar do to merit this extreme measure?
The problem in one sense was relatively simple and possibly an everyday occurrence in a banker's life. One of the borrowers of the Bank, a cement company, became sick with mounting losses and approached the Bank for restructuring assistance. The economy was undoubtedly passing through a difficult phase at that time. The 1971 war with Pakistan on the issue of Bangladesh had left many scars and several marginal companies were facing considerable difficulties. The State Bank of India, being the largest Bank was involved with most such enterprises and was always ready and willing to give a helping hand to rescue these companies. What made the problem difficult with respect to this specific company was the strong assessment by the Bank that much of the difficulties of the company were brought about due to gross mismanagement, and given this assessment, the Bank insisted that as a condition precedent to implementing the restructuring package, the Chairman of the company who was also the CEO should step down from the management and a professional management should take over the Company's management.
This was a standard prescription by the Bank in similar circumstances, and it was invariably resisted by the promoters till they reached a stage when it was difficult for them to carry on without the Bank's help. In this specific case also the promoter strongly resisted any attempt to dislodge him from the management position but the Bank held its ground.
But then this promoter turned out to be different. He was a friend of Sanjay Gandhi, son of then Prime Minister of India, Mrs. Indira Gandhi and decided to take his case directly to him. To Sanjay Gandhi who was grappling with more serious affairs of the country, this turned out to be a minor irritant. He called the Finance Minister and asked him to direct the Bank to waive this requirement. As far as he was concerned he had given his decision and that should have seen the end of the matter. But the problem was the Government was dealing with a different person, Talwar who was not used to taking orders from the Government.
The Finance Minister telephoned Talwar and asked him not to insist on a change in management as a condition precedent to restructuring. Talwar called for the details from the department and having satisfied himself with the merits of the case, informed the Finance Minister that it would be difficult for the Bank to waive the requirement of change in management. The Finance Minister sent for Talwar and told him that he had received instructions from "the highest authority" in the country who expected him to carry out the orders without demur. Talwar stood his ground and told the Finance Minister in no uncertain terms that there was no way for him to waive this requirement and the Bank's position would remain unchanged. When this was communicated to Sanjay Gandhi, he must have been quite amused. During the period of about a little more than a year since the Emergency was declared, he had never met anybody who either disagreed with him or refused to carry out his orders. He decided to send for Talwar to personally talk to him and was shocked to hear from his intermediaries that Talwar refused to come and see him on the ground that he held no constitutional authority and he was accountable only to the Finance Minister. Sanjay Gandhi's response was swift and clear. He told the Finance Minister to sack Talwar.
But the Finance Minister faced two sets of problems. Talwar, during the seven years he was the Chairman of the Bank, had achieved a high sense of personal reputation and his removal from the office for what could be called a trivial issue would send shock waves in the industry.
The Finance Minister could, however, manage this, because this was a period of emergency and what could have caused a stir in the normal times, would pass off as not unusual in the extraordinary circumstances prevailing in the country. The second problem was much more intractable. When the matter was referred to the Legal department, the Legal department pointed out to the specific provision in the State Bank of India Act which guaranteed the Chairman the special protection against removal without sufficient cause. The Finance Minister, therefore, felt that a better course of action would be to offer Talwar a different assignment or seek his resignation. He sent for Talwar again and told him that the Government was planning to set up a Banking Commission to make recommendations with regard to the restructuring of the functioning of the banking system and whether he would be willing to accept the Chairmanship of the Commission.
Without batting an eyelid, Talwar told the Finance Minister that he would indeed be happy to head the Commission and he could carry out this job simultaneous with his existing assignment as Chairman of State Bank. When the Finance Minister looked somewhat uncomfortable with this suggestion, Talwar very calmly looked the Finance Minister in his eyes and told him "Mr. Minister you seem to be very particular that I should not continue as the Chairman of the State Bank of India, is that correct?" The Finance Minister replied. "Yes Mr. Talwar, you know what the problem is. We all have the highest regard for your abilities but unfortunately you do not seem to be very flexible on this one issue which is of great importance to the highest authority in the country. If you do not want to accept any other position, I may have no option but to seek your resignation or in the alternative, to dismiss you from service. This would be extremely painful to me but I would be left with no other option." Talwar replied, "Mr. Minister I have no intention of resigning from my position. It is entirely up to you to decide whether you want to dismiss me. In any case, I have just about a little more than a year left in my second term and I see no reason why you should not allow me to complete it." The Finance Minister looked pained and miserable.
He terminated the interview and hoped that some solution would be found. He reported the matter to Sanjay Gandhi who was infuriated and asked the CBI to investigate Talwar to find out whether there were any grounds on which he could be dismissed in terms of Talwar's personal reputation for honesty and integrity was quite well known and in the normal course it would have been virtually impossible for any investigating agency to charge him with any misconduct. He, however, had two chinks in his armour. One was his almost monthly visits to Pondicherry which attracted widespread attention both within the Bank and in the political circles. His attachment to the Mother and the Aurobindo Ashram was well known and he made it clear to the Government when this issue once came up for discussion that he needed these visits for what he called "recharging his batteries" and that if as a condition of his employment he were to stop these visits, he would as well step down from the Bank. In any case, this could not be construed as a sufficient cause for his dismissal in terms of the Act. The second one was a little more serious. Talwar had sent appeals on behalf of the Ashram to a large number of industrialists, many of whom were clients of the Bank, seeking donations for the Auroville project. Those of us who were close to him, feared that the Central Investigative Agency could focus on this issue and charge him with abuse of authority. While Talwar himself was completely unperturbed by the reported investigation, we came to know from several sources that the Agency was meeting several industrialists who had given donation to the project with a view to taking from them a statement that they were coerced into giving this donation at the instance of Talwar.
At the end of the investigation, two things became very clear to the Agency. One was that not a single industrialist was willing to say that Talwar either spoke to them or in any way tried to persuade them to make the donation. The second was what all Talwar did was to forward to these clients an appeal signed by Prime Minister, Ms. Gandhi and the Secretary General of the United Nations, U Thant commending the Auroville project for support.
The Agency found that under these circumstances, there was no way in which they could charge Talwar with abuse of his position. While the CBI closed the case, as far as the Finance Minister was concerned, it was back to square one and he faced the unpleasant task of reporting back to his political master his failure to carry out his diktat. Sanjay Gandhi lost his patience. He directed the Finance Minister to amend the State Bank of India Act to provide for a summary dismissal of the Chairman.
The Legislation amending the State Bank of India Act was passed in record time and received the assent of the President without any delay. Armed with the new provision in the Act, the finance Minister summoned Talwar once again and told him that if he did not resign from the service, there was no alternative but to remove him in terms of the new provision. But, Talwar was defiant. He told the Finance Minister that he had no intention of resigning and the Finance Minister could take whatever action he deemed appropriate. On the evening of the 4th of August, 1976 Talwar received a fax message from the Finance Minister sanctioning him 13 months leave and asking him to hand over charge to the Managing Director. It is amazing that with all the powers in their hands, the Government could not summon up enough courage to dismiss Talwar, but instead gave him leave preparatory to retirement for as long as 13 months, which he did not ask for!! This was the respect he commanded in the industry.
Talwar left the Bank promptly ‪at 5.30 p.m. which was his usual time of departure. There was hardly anybody to see him off. Everyone was scared even to be seen to be associated with him. I had by then left the Bank service and joined the National Institute of Bank Management.
The residence of the Chairman of the State Bank was just across the road and as soon as I received intimation that he had reached his home, I walked across to meet him. I found him smiling and cheerful. Extending his hand to greet me on my birthday (which by a curious coincidence happened to be 4th August) he said, "Vaghul, look at the Divine will. What a pleasure it is to be gifted with His blessings."
I did not know what to say. I mumbled something to the effect that the Divine always tested His true bhaktasand every such test would only serve to reinforce the faith. He looked me at my eyes and said "How can you call this a test? As far as I am concerned, I am only an instrument of the Divine and His Will is the only thing that is important to me. If you see this as a suffering, it only shows your ignorance. We cannot sit in judgment over the Divine will." I then said, "I agree, Sir that we have to accept the Divine Will with humility." But he was not finished with his lesson. "Where is the question of accepting or not accepting? You have to learn to enjoy all the time the Divine play. The work in the Bank is over. What the Divine has in store for me I do not know. Whatever it is, I will serve the Divine with devotion and always enjoy being His instrument." I could only think of one example when I looked at him – the picture of Rama when he was told by Kaikeyi that he was not to be crowned as the King but had to go to the forest for 14 years. The Tamil poet Kamban says that when he heard this pronouncement from Kaikeyi, Rama's face resembled that of a lotus with a full bloom. He was happy to carry out the behest of his father. In the case of Talwar, it was the behest of the Divine. That was the only difference.
*Narayanan Vaghul*
The author is the Former Chairman of ICICI Bank Limited. He is widely recognized in India for his role in pioneering the concept of the Universal Banking Model that laid the foundation for a new era in Indian Banking. He was mentored by Late Mr. R.K. Talwar during his tenure at State Bank of India and one of the few whom Shri Talwar confided in.

Tuesday, 5 December 2017

What Is Full and Final Settlement? A Complete Guide for HR Professionals

 

SEO Title: What Is Full and Final Settlement? Complete Guide for HR Professionals
Meta Description: Learn what Full and Final Settlement is, what components may be included and how HR and payroll professionals manage employee exit settlements.

When an employee leaves an organisation, HR and payroll teams need to complete the employee's financial and administrative closure. This process is commonly known as Full and Final Settlement, or F&F Settlement.

What Is Full and Final Settlement?

Full and Final Settlement is the process of calculating and settling amounts payable to or recoverable from an employee after separation from an organisation.

The final calculation depends on the employee's employment terms, attendance, leave records, company policies and applicable legal requirements.

Components That May Be Included

Depending on the situation, an F&F settlement may include:

  • Salary payable until the last working day

  • Leave encashment, where applicable

  • Incentives or approved reimbursements

  • Bonus or other eligible payments

  • Recovery of advances or loans

  • Notice period adjustments

  • Other authorised deductions or recoveries

  • Gratuity, where applicable

Step-by-Step F&F Process

Step 1: Confirm Employee Exit Details

Verify:

  • Last working day

  • Resignation or termination details

  • Notice period status

  • Attendance

  • Pending leave

Step 2: Calculate Salary Payable

Calculate salary for the applicable period based on attendance and payroll policy.

Step 3: Review Leave Balance

Determine whether leave encashment or other leave-related adjustments apply.

Step 4: Identify Recoveries

Review possible recoveries such as:

  • Salary advances

  • Employee loans

  • Notice period recovery

  • Other approved recoveries

Step 5: Calculate Final Payable Amount

The payroll team combines eligible earnings and deductions to determine the final settlement amount.

Why F&F Knowledge Is Important

Full and Final Settlement requires coordination between HR, payroll, finance and sometimes other departments.

A practical understanding of employee exits can help HR professionals manage the process more efficiently.

Learn Practical HR & Payroll at Palium Skills

The Palium Skills program includes practical exposure to Full & Final Settlement along with payroll processing, statutory concepts, Advanced Excel, HR MIS, HRMS/payroll software and HR analytics.

Contact Palium Skills

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

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

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

Friday, 1 December 2017

How to Install Selenium with Java and Eclipse: Complete Setup Guide

 

Introduction

Selenium is one of the most popular open-source tools for automating web application testing. It enables software testers to automate browser interactions, validate application functionality and execute repetitive test scenarios.

Java is a widely used programming language for developing Selenium automation scripts. When combined with Eclipse IDE and Maven, it provides a convenient environment for building and managing automation testing projects.

For beginners, configuring the development environment is the first important step towards learning Selenium Automation Testing.

This tutorial explains how to install Selenium with Java and Eclipse, configure the required dependencies and execute your first browser automation program.

1. System Requirements for Selenium Java Setup

Before starting the installation, ensure that your computer meets the basic requirements.

Hardware requirements:

  • A computer with a modern processor.

  • At least 8 GB RAM recommended for comfortable development.

  • Sufficient storage for the IDE, JDK and browser.

Software requirements:

  • Java Development Kit (JDK).

  • Eclipse IDE.

  • Google Chrome or another supported browser.

  • Selenium WebDriver.

  • Maven, preferably for dependency management.

Using compatible software versions helps prevent installation and execution problems.

2. Install Java Development Kit (JDK)

Java is required to develop and execute Selenium automation scripts.

Step 1: Download JDK

Download a supported JDK version from a trusted distribution such as Oracle JDK or Eclipse Temurin.

Install the JDK by following the installation instructions.

Step 2: Verify Java Installation

Open Command Prompt in Windows and execute:

java -version

To verify the Java compiler, execute:

javac -version

If both commands display the installed version, Java is available from the command line.

Step 3: Configure JAVA_HOME

Set the JAVA_HOME environment variable to the JDK installation directory.

For example:

JAVA_HOME=C:\Program Files\Java\jdk-17

Add the JDK bin directory to the system PATH if it is not already available.

The actual directory depends on your installed JDK version and location.

3. Install Eclipse IDE

Eclipse is a popular integrated development environment used for Java programming.

Step 1: Download Eclipse

Download Eclipse IDE from the official Eclipse website.

Choose the Java Developers package or another suitable Java development distribution.

Step 2: Install Eclipse

Run the Eclipse installer and complete the installation.

Step 3: Launch Eclipse

Open Eclipse and select a workspace directory.

The workspace stores your Java projects and related development files.

4. Create a Java Project in Eclipse

Follow these steps:

  1. Open Eclipse IDE.

  2. Select File.

  3. Choose New.

  4. Select Java Project.

  5. Enter a project name, such as SeleniumAutomation.

  6. Select an appropriate JDK.

  7. Click Finish.

Your Java project is now ready.

You can create a package and a Java class to organise your automation scripts.

5. Add Selenium WebDriver Dependencies

There are two common ways to add Selenium libraries to a Java project.

Method 1: Using Maven

Maven is recommended because it simplifies dependency management.

Create a Maven project in Eclipse and open the pom.xml file.

Add the following Selenium dependency:

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

The dependency version shown is an example. Use a current compatible Selenium release for your project.

Save the file. Maven will download the required Selenium libraries automatically.

Method 2: Adding Selenium JAR Files Manually

Alternatively, download the Selenium Java libraries from the official Selenium website.

In Eclipse:

  1. Right-click your Java project.

  2. Select Build Path.

  3. Choose Configure Build Path.

  4. Open the Libraries tab.

  5. Select Add External JARs.

  6. Select the required Selenium JAR files.

  7. Apply the changes.

For beginners, Maven is generally easier to maintain as the project grows.

6. Install and Configure Google Chrome

Install Google Chrome or another supported browser.

Modern Selenium versions include Selenium Manager, which can automatically locate or obtain the appropriate browser driver when required, provided the environment allows it.

This eliminates much of the traditional manual driver configuration.

7. Write Your First Selenium Java Program

Now that the development environment is ready, create your first Selenium automation script.

In Eclipse:

  1. Open the SeleniumAutomation project.

  2. Create a package called automation.

  3. Create a Java class named FirstSeleniumTest.

  4. Enter the following code.

package automation;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstSeleniumTest {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

        driver.get("https://www.google.com");

        System.out.println(
            "Page Title: " + driver.getTitle()
        );

        driver.quit();
    }
}

Understanding the Program

WebDriver: Provides the interface for browser automation.

ChromeDriver: Creates a Chrome browser automation session.

driver.get(): Opens the specified website.

driver.getTitle(): Retrieves the title of the current web page.

driver.quit(): Ends the browser session.

8. Execute Your Selenium Automation Script

After writing the program:

  1. Save the Java file.

  2. Right-click the class in Eclipse.

  3. Select Run As.

  4. Choose Java Application.

If the configuration is correct, Chrome should open, navigate to Google and display the page title in the Eclipse console.

Congratulations! You have successfully executed your first Selenium Java automation program.

9. Common Selenium Installation Problems

Beginners may encounter several configuration issues.

Java Not Recognised

If the system displays an error stating that Java is not recognised, verify JAVA_HOME and PATH settings.

Maven Dependency Errors

Check your internet connection, dependency configuration and Maven project refresh.

Browser Driver Problems

Verify that your browser is supported and that Selenium Manager can access the necessary driver resources.

Selenium Import Errors

Check whether the Selenium dependency has been added correctly to the project build path.

Browser Session Creation Errors

Check browser availability, browser compatibility, driver configuration and system permissions.

10. What Should You Learn After Installation?

Installing Selenium is only the first step.

To become proficient in automation testing, continue with:

  • Selenium WebDriver commands.

  • Locators and XPath.

  • CSS selectors.

  • Handling dropdowns and alerts.

  • Browser windows and frames.

  • Synchronisation and waits.

  • TestNG and JUnit.

  • Maven project management.

  • Page Object Model.

  • Data-driven testing.

  • Selenium Grid.

  • Jenkins and CI/CD integration.

You should also practise developing an end-to-end automation framework.

Learn Selenium with Java at Palium Skills

Palium Skills offers structured Selenium Automation Testing Training for freshers, graduates and working professionals.

The programme covers Java fundamentals, Selenium WebDriver, automation frameworks and practical project exercises.

Training highlights:

  • Java programming for automation testing.

  • Selenium installation and configuration.

  • WebDriver commands and locators.

  • XPath and CSS selectors.

  • TestNG and Maven.

  • Page Object Model framework.

  • Hands-on automation assignments.

  • Real-time project practice.

  • Interview preparation.

Training modes:

Classroom Training: South Kolkata and Salt Lake centres.

Live Online Training: Instructor-led sessions for learners across India.

Whether you are a beginner or an experienced manual tester, Palium Skills can help you develop practical automation testing knowledge.

Contact Palium Skills

Website: www.paliumskills.com

Call: 8420594969 / 7044871915

WhatsApp: 9903130500

Email: info@paliumskills.com

Frequently Asked Questions

1. Is Java required for Selenium?

Java is not compulsory because Selenium supports multiple programming languages. However, Java is a popular choice for automation testing.

2. Which Eclipse version should I install?

Choose a current Eclipse IDE distribution that supports your installed JDK.

3. Is Maven compulsory for Selenium?

No. Selenium libraries can be added manually, but Maven makes dependency management easier.

4. Do I need to download ChromeDriver separately?

Not necessarily. Modern Selenium versions include Selenium Manager, which can manage browser drivers automatically in supported environments.

5. Can beginners learn Selenium with Java?

Yes. Beginners can start with Java fundamentals and gradually progress to browser automation and framework development.

6. Where can I learn Selenium Java in Kolkata?

Palium Skills offers classroom Selenium training at its South Kolkata and Salt Lake centres, along with instructor-led live online sessions.

Conclusion

Installing Selenium with Java and Eclipse is the first practical step towards developing browser automation scripts. By configuring JDK, Eclipse, Maven and Selenium WebDriver correctly, learners can establish a suitable environment for automation testing.

Once the setup is complete, the next step is to practise browser commands, element identification, waits and framework development.

Join Palium Skills for Selenium Automation Testing Training through classroom or live online sessions.

Wednesday, 1 November 2017

Selenium Locators: XPath, CSS Selector, ID and Name Explained with Examples



Introduction

Selenium WebDriver is widely used for automating web applications. One of the most important skills in Selenium automation is identifying and locating web elements accurately.

Before Selenium can click a button, enter text into a field, select an option or verify information, it must identify the relevant element on the webpage. Selenium uses locators to find these elements.

Understanding locators such as ID, Name, Class Name, CSS Selector and XPath is essential for developing reliable automation scripts.

In this guide, we will explore the most commonly used Selenium locators with practical Java examples.

What Are Locators in Selenium?

Locators are methods used by Selenium WebDriver to identify HTML elements on a webpage.

For example, consider a login form containing:

  • Username field

  • Password field

  • Login button

Selenium needs to locate each element before interacting with it.

A typical HTML element may look like this:

<input id="username" name="user" type="text">

Selenium can identify this field using its ID or Name attribute.

1. ID Locator

The ID locator identifies an element using its unique HTML ID attribute.

HTML example:

<input id="email" type="text">

Java example:

driver.findElement(By.id("email")).sendKeys("test@example.com");

Advantages:

  • Simple and easy to use.

  • Usually fast and reliable.

  • Works well when IDs are unique and stable.

Limitation: Some websites generate dynamic IDs, which may change between sessions.

2. Name Locator

The Name locator identifies an element through its HTML Name attribute.

HTML example:

<input name="password" type="password">

Java example:

driver.findElement(By.name("password")).sendKeys("Test@123");

Name locators are useful for forms where elements have meaningful and stable name attributes.

If multiple elements share the same name, Selenium may locate the first matching element when using findElement().

3. Class Name Locator

The Class Name locator identifies elements using their CSS class attribute.

HTML example:

<button class="login-button">Login</button>

Java example:

driver.findElement(By.className("login-button")).click();

Class Name is useful when elements share a common class.

However, By.className() accepts a single class name, not a compound class string containing multiple classes.

4. Tag Name Locator

Tag Name identifies elements using HTML tags such as input, button, a, div or select.

Java example:

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

It can also be used to retrieve multiple elements:

List<WebElement> buttons =
    driver.findElements(By.tagName("button"));

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

Tag Name is particularly useful when working with groups of similar elements.

5. CSS Selector in Selenium

CSS Selector is a powerful locator strategy that identifies elements using CSS selector syntax.

ID-based CSS Selector:

driver.findElement(By.cssSelector("#email"));

Class-based CSS Selector:

driver.findElement(By.cssSelector(".login-button"));

Attribute-based CSS Selector:

driver.findElement(
    By.cssSelector("input[name='password']")
);

Combining attributes:

driver.findElement(
    By.cssSelector("input[type='text'][name='username']")
);

CSS Selectors are generally concise and useful for locating elements through IDs, classes, attributes and relationships.

6. XPath in Selenium

XPath is a query language used to navigate through elements in an HTML or XML document.

It is especially useful when elements do not have unique IDs or when locating elements through their text, attributes or relationships.

Absolute XPath

An absolute XPath starts from the root of the HTML document and follows the complete element hierarchy.

Example:

driver.findElement(
    By.xpath("/html/body/div/form/input")
);

Absolute XPath can be fragile because changes in the page structure may break the locator.

Relative XPath

Relative XPath starts from a selected point in the document.

Example:

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

Relative XPath is generally preferred because it is more flexible.

XPath Using Text

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

XPath Using Contains

driver.findElement(
    By.xpath("//button[contains(@class,'login')]")
).click();

XPath Using Starts-With

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

XPath Using Multiple Attributes

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

These techniques are particularly useful when automating dynamic web applications.

7. Selenium Locators Comparison

LocatorExampleTypical use
IDBy.id("email")Unique element ID
NameBy.name("user")Form fields
Class NameBy.className("btn")Elements with a class
Tag NameBy.tagName("input")Groups of HTML elements
CSS SelectorBy.cssSelector("#email")Flexible attribute and class selection
XPathBy.xpath("//input[@id='email']")Complex element relationships

There is no single locator that is best for every situation. Choose a locator based on uniqueness, stability, readability and maintainability.

8. Practical Selenium Java Example

The following example demonstrates locating and interacting with elements using different locator strategies.

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

public class LocatorExample {

    public static void main(String[] args) {

        WebDriver driver = new ChromeDriver();

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

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

        driver.findElement(By.name("password"))
              .sendKeys("Test@123");

        driver.findElement(
            By.cssSelector("button.login-button")
        ).click();

        driver.quit();
    }
}

Replace the example URL and locator values with those from your own test application.

9. Best Practices for Using Selenium Locators

Follow these practices to build stable automation scripts:

  1. Prefer unique and stable IDs whenever available.

  2. Use Name attributes when they are meaningful and reliable.

  3. Use CSS Selectors for concise attribute-based identification.

  4. Use relative XPath for complex element identification.

  5. Avoid fragile absolute XPath expressions.

  6. Avoid relying on automatically generated IDs that frequently change.

  7. Use browser developer tools to inspect HTML elements.

  8. Keep locators readable and maintainable.

  9. Validate that a locator identifies the intended element.

  10. Use explicit waits when elements need time to become available or interactable.

Frequently Asked Questions

1. Which locator is best in Selenium?

A unique, stable ID is often a good first choice. CSS Selector and XPath are useful alternatives depending on the webpage structure.

2. What is the difference between XPath and CSS Selector?

Both can identify elements using attributes and relationships. XPath also supports text-based matching and flexible navigation through the document hierarchy.

3. Can Selenium use multiple locators for the same element?

Yes. An element may be identifiable using different locator strategies. You should choose the most reliable and maintainable one.

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

findElement() returns the first matching element and throws a NoSuchElementException if no match exists. findElements() returns a list of matching elements and returns an empty list when none are found.

5. Do I need to learn XPath for Selenium automation?

Yes. XPath is an important skill, particularly when working with complex or dynamic web applications.

Learn Selenium Automation Testing with Palium Skills

Want to build practical skills in Selenium automation testing? Palium Skills offers structured training designed for freshers, manual testers and working professionals.

The training covers:

  • Selenium WebDriver with Java and Python

  • XPath and CSS Selector techniques

  • TestNG and PyTest frameworks

  • Page Object Model (POM)

  • Automation framework development

  • API testing and practical automation projects

  • Interview preparation and career guidance

Training modes: Classroom training at South Kolkata and Salt Lake centres, along with 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.

Visit Palium Skills to explore Selenium and Playwright automation testing training.

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.

How Does Payroll Work in India? A Step-by-Step Guide

  How Does Payroll Work in India? Step-by-Step Guide   Summary: Understand how payroll works in India, including salary structure, attendan...