简体   繁体   中英

Can we pass object of a List<WebElement> to a function as a parameter?

I am automating a web application right now.I have used a list array to locate few objects inside a container.All I need to do is that that I have to mouse-hover to the first element and click on the same.But the mouse-hover method I have written in another class as common function.So can I use the object of the list array to pass to the mouse-hover method in any way.?

屏幕拍摄

To Find the elements in the container .

 By by = By.xpath("//ul[@id='sortable']");
 List<WebElement> featureList= element.findElements(by.tagName("a"));


//Mouse-hover method

public static void moveMouseOver(WebDriver driver, By locator) {
        WebElement element = waitForElementPresent(driver, locator);
        (new Actions(driver)).moveToElement(element).build().perform();
    }


Here can I change the 'By Locator' argument to replace with List array object ?

You could try changing moveMouseOver to something like :

    public static void moveMouseOver(WebDriver driver, WebElement... webElements){
    if(null != webElements){
        for(WebElement webEl : webElements){
           // do something here
         }
      }
     }

and then call this as

moveMouseOver(driver, ((WebElement[])featureList.toArray()))

Please check for syntax errors if any as I have written this up here only and not checked in an IDE

You can change your method to:

public static void moveMouseOver(WebDriver driver, By locator, String...action) {
    List<WebElement> lstElements = driver.findElements(locator);
    for (WebElement webelement : lstElements){
        if (action.length > 0 && action.equalsIgnoreCase("click"))
            (new Actions(driver)).moveToElement(element).click().build().perform();
        else
            (new Actions(driver)).moveToElement(element).build().perform();
}

In such a scenario it will work for single element also and for multiple and you won't be required to change usage in previous scenarios, though u need handle different cases in future as this one handles click only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM