使用TestNG框架在Selenium Java中出现Element Not displayed Exception后继续运行后续步骤

问题描述 投票:0回答:1

我有一个代码来检查一个元素是否显示。如果显示,则应写为“通过”,如果元素不存在,则测试应写为“失败”,并应继续执行后续步骤。我也添加了 Try catch 块,但如果元素不存在,脚本仍然会停在此处。

这是我的代码:

//Click Bautowatch
        WebElement bautoWatch = driver.findElement(By.xpath("//span[contains(text(),'Bautowatch')]"));
        bautoWatch.click();
        Thread.sleep(1000);

        //Click Bautowatch Process
        WebElement bautoProcess = driver.findElement(By.xpath("//span[contains(text(),'Process')]"));
        bautoProcess.click();
        Thread.sleep(1000);

       //Check Process header is displayed to confirm Bautowatch Process page is loaded
            try {
                WebElement processHeader = driver.findElement(By.xpath("(//div[contains(text(),'Processnew')])[1]"));
                assert processHeader.isDisplayed();
                Thread.sleep(1000);
                System.out.println("Bautowatch Process - Pass");
                Properties.screenshotMethod(driver, "Bautowatch Process - Pass");
            } catch (NoSuchElementException e) {
                System.out.println("Bautowatch Process - Fail");
                Properties.screenshotMethod(driver, "Bautowatch Process - Fail");
            }

       //Click Bautowatch Connector
        WebElement bautoConnector = driver.findElement(By.xpath("(//span[contains(text(),'Connector')])[1]"));
        bautoConnector.click();
        Thread.sleep(1000);

        //Check Connector header is displayed to confirm Bautowatch Connector page is loaded
        WebElement connectorHeader = driver.findElement(By.xpath("(//div[contains(text(),'Connector')])[1]"));
        try {
            assert connectorHeader.isDisplayed();
            Thread.sleep(1000);
            System.out.println("Bautowatch Connector - Pass");
            Properties.screenshotMethod(driver,"Bautowatch Connector - Pass");
        }catch (AssertionError e){
            System.out.println("Bautowatch Connector - Fail");
            Properties.screenshotMethod(driver,"Bautowatch Connector - Fail");
        }

如果任何元素不存在,我的脚本应标记为失败并继续运行后续步骤

java selenium-webdriver intellij-idea testng
1个回答
0
投票

使用

findElements
代替
findElement

findElements
会比前者更好地处理
NoSuchElementException

findElement - 如果未找到元素,则抛出 NoSuchElementException,并中止执行

findElements - 如果未找到匹配元素,则返回空列表并继续执行下一行代码

请参阅下面的示例代码:

List<WebElement> processHeader = driver.findElements(By.xpath("(//div[contains(text(),'Processnew')])[1]"));
if (processHeader.size() >= 1) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}
© www.soinside.com 2019 - 2024. All rights reserved.