In Selenium automation, creating reusable methods is a best practice that helps reduce code duplication and improves maintainability within the framework. Instead of writing the same logic multiple times, we can place common actions into utility methods and call them whenever needed.
Reusable methods can be created for tasks such as:
- Handling input fields
- Selecting values from dropdowns
- Clicking buttons safely
- Waiting for elements to appear
Using reusable methods not only simplifies the test scripts but also makes the framework easier to maintain and extend in the long run.
Below is an example of a reusable method for handling dropdown elements in Selenium with java:
🔄 Reusable Dropdown Method with Switch-Case
import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select;
public class SeleniumUtils {
/**
* Reusable method to handle dropdown selection
*
* @param element - Dropdown WebElement
* @param selectionType - "text", "index", or "value"
* @param selectionValue - The value to select (text, index, or value)
*/
public static void selectDropdown(WebElement element, String selectionType, String selectionValue) {
Select select = new Select(element);
switch (selectionType.toLowerCase()) {
case "text":
select.selectByVisibleText(selectionValue);
break;
case "index":
try {
int index = Integer.parseInt(selectionValue);
select.selectByIndex(index);
} catch (NumberFormatException e) {
System.out.println("Invalid index value: " + selectionValue);
}
break;
case "value":
select.selectByValue(selectionValue);
break;
default:
System.out.println("Invalid selection type! Use 'text', 'index', or 'value'.");
}
}
}
✅ How to use in your test script:
// Example usage
WebElement countryDropdown = driver.findElement(By.id(“country”));
// Select by visible text
SeleniumUtils.selectDropdown(countryDropdown, “text”, “India”);
// Select by index
SeleniumUtils.selectDropdown(countryDropdown, “index”, “3”);
// Select by value
SeleniumUtils.selectDropdown(countryDropdown, “value”, “IN”);