Working with Collections in Java for Selenium Testing
🔹 What Are Collections in Java?
The Java Collections Framework provides classes and interfaces to store and manipulate groups of data as a single unit (like arrays, lists, sets, maps). Commonly used collections include:
List
Set
Map
Queue
They are essential when dealing with multiple elements in Selenium, such as web elements or data values.
🔹 Why Use Collections in Selenium Testing?
In Selenium automation, we often need to:
Handle multiple web elements (e.g., all links on a page)
Store test data or expected values
Validate lists, tables, or dropdown options
Collections help manage and manipulate such data efficiently.
🔹 Common Use Cases with Examples
1. Handling Multiple Web Elements
java
Copy
Edit
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());
for (WebElement link : links) {
System.out.println(link.getText());
}
2. Storing and Validating Dropdown Options
java
Copy
Edit
Select dropdown = new Select(driver.findElement(By.id("country")));
List<WebElement> options = dropdown.getOptions();
List<String> actualOptions = new ArrayList<>();
for (WebElement option : options) {
actualOptions.add(option.getText());
}
List<String> expectedOptions = Arrays.asList("India", "USA", "UK");
// Validate
Assert.assertEquals(actualOptions, expectedOptions);
3. Using Set to Remove Duplicates
java
Copy
Edit
List<WebElement> elements = driver.findElements(By.className("item-name"));
Set<String> uniqueItems = new HashSet<>();
for (WebElement el : elements) {
uniqueItems.add(el.getText());
}
System.out.println("Unique item count: " + uniqueItems.size());
4. Using Map to Store Key-Value Data
java
Copy
Edit
Map<String, String> testData = new HashMap<>();
testData.put("username", "admin");
testData.put("password", "12345");
driver.findElement(By.id("username")).sendKeys(testData.get("username"));
driver.findElement(By.id("password")).sendKeys(testData.get("password"));
🔹 Useful Tips
Prefer List when order matters (e.g., dropdowns).
Use Set to remove duplicates (e.g., filtering unique elements).
Use Map for key-value pairs (e.g., credentials, label-value pairs).
Collections are often used with loops or Streams to iterate and process data.
🔹 Conclusion
Collections in Java are powerful tools that enhance Selenium tests by allowing you to:
Work efficiently with groups of elements
Compare and validate lists
Organize and reuse data
Understanding and using the right collection type improves the maintainability and robustness of your Selenium automation framework.
Learn Selenium JAVA Course in Hyderabad
Read More
Handling Exceptions in Selenium Test Scripts
Using Loops and Conditions to Control Test Flow
⚙️ Java + Selenium Programming Concepts
Running Tests with TestNG XML Suite
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment