在执行实际操作之前对 Web 元素进行一些标准验证

正如标题所示,我在实际操作之前对网络元素进行一些标准检查。检查该元素是否显示并启用。我想将这两个检查分开,因为我想要一个失败的具体原因。我觉得下面的代码太长了。


任何建议将不胜感激。


Boolean isActionSuccess = false; 

        if (currentObject.isDisplayed()) {

            if (currentObject.isEnabled()) {


                // move to the object before clicking

                CommonFunctions.silentWait(1);

                actionToE.moveToElement(currentObject).perform();


                if (!actionPar.isEmpty()) {

                    // do something else

                } else {

                    currentObject.sendKeys(Keys.ARROW_UP);

                    isActionSuccess = true;

                }


            } else {

                System.out.println("Web Element is disabled!");

            }


        } else {

            System.out.println("Web Element is not displayed!");

        }


至尊宝的传说
浏览 83回答 3
3回答

ITMISS

这里最好的做法是将它们分成自己的小函数并返回布尔值。喜欢Boolean isElementDisplayed(WebElement element){    if (element.isDisplayed())        return true;    System.out.println(element + " is not displayed!");    return false;}Boolean isElementEnabled(WebElement element){    if (element.isEnabled())        return true;    System.out.println(element + " is not enabled!");    return false;}但我还建议在执行 moveToElement 之后调用 isElementDisplayed,因为某些浏览器对“显示”的含义有不同的考虑。您还可以使用 try catch 来记录每个函数的异常。

天涯尽头无女友

  Boolean isActionSuccess = false;         CommonFunctions.silentWait(1);        actionToE.moveToElement(currentObject).perform();        if (CommonFunctions.isElementDisplayed(currentObject)) {            if (CommonFunctions.isElementEnabled(currentObject)) {                if (!actionPar.isEmpty()) {                    // do something                    }                } else {                    currentObject.sendKeys(Keys.ARROW_LEFT);                    isActionSuccess = true;                }            }        }

开满天机

在使用Selenium执行自动化测试时,您不需要在实际操作之前对 Web 元素进行任何额外的标准检查。根据记录,每增加一行代码都会导致额外的指令和指令周期。相反,您需要优化您的代码/程序。如果你的用例是调用click()或者sendKeys()不需要调用isDisplayed()或者isEnabled()单独去检查。相反,您需要结合使用WebDriverWait和ExpectedConditions来等待预定义的时间段(根据测试规范)。例子:presenceOfElementLocated()是检查页面 DOM 上是否存在元素的期望。这并不一定意味着该元素是可见的。new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("button.nsg-button")));visibilityOfElementLocated()是检查元素是否存在于页面 DOM 上并且可见的期望。可见性是指元素不仅能显示,而且高度和宽度都大于0。new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button.nsg-button")));elementToBeClickable()是检查元素是否可见并启用以便您可以单击它的期望。new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='nsg-button']"))).click();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java