I need to combine two methods into one method(two methods only xpath values are changing, rest of the functions are same). Two methods are performing same function except xpath value. How I can use this two xpath value in one method and make it two method into one method.
NAV_MENU_ITEMS_LIST= driver.findElement(By.xpath(mat-input-0))
NAV_SUB_MENU_ITEMS_LIST= driver.findElement(By.xpath(//span[text()=' Quick Login ']))
private void methodOne(String menuItemName) {
NAV_MENU_ITEMS_LIST.findBy(text(menuItemName))
.click();
log.info("Navigating to " menuItemName);
}
private void methodTwo(String subMenuItemName) {
NAV_SUB_MENU_ITEMS_LIST.findBy(text(subMenuItemName))
.click();
log.info("Navigating to " subMenuItemName);
}
CodePudding user response:
You mean like:
NAV_MENU_ITEMS_LIST= driver.findElement(By.xpath(mat-input-0))
NAV_SUB_MENU_ITEMS_LIST= driver.findElement(By.xpath(//span[text()=' Quick Login ']))
// public! (for example)
public void methodOne(String menuItemName) {
methodInternal(menuItemName, NAV_MENU_ITEMS_LIST);
}
// public!
public void methodTwo(String subMenuItemName) {
methodInternal(subMenuItem, NAV_SUB_MENU_ITEMS_LIST);
}
with:
private static void methodInternal(String item, WebElement elem /*??*/) {
elem.findBy(text(item)).click();
log.info("Navigating to {}", item);
}
!?
CodePudding user response:
If you have two or more methods with identical method body and only internal value changes, you could simply pass the variable data as parameters to the method. In your case,
private void commonizedMethod(String menuItemName, WebElement element) {
element.findBy(text(menuItemName)).click();
log.info("Navigating to: " menuItemName);
}
Alternatively, you could resolve for the element internally by passing the Xpath to the method
private void commonizedMethod(String menuItemName, WebDriver driver, String xpath) {
WebElement element = driver.findElement(By.xpath(xpath));
element.findBy(text(menuItemName)).click();
log.info("Navigating to: " menuItemName);
}
If the driver is a global parameter, you don't need to pass it in the method.
