如果找不到Xpath,我的脚本不会移动到其他测试用例并停止一切并退出。我正在使用selenium testng框架工作

时间:2016-02-02 05:53:11

标签: selenium

//getElementByXPath function for static xpath
public WebElement getElementByXPath(String Key){
    try{
        //This block will find element using Key value from web page and return It.
        return driver.findElement(By.xpath(Object.getProperty(Key)));
    }catch(Throwable t){
        //If element not found on page then It will return null.
        Add_Log.debug("Object not found for key --"+Key);
        return null;
    }
}

此处未找到某个元素时,我的脚本会停止并退出。但我希望它只是给我错误,所以我可以在测试结果中使用它并转到下一个测试用例。

2 个答案:

答案 0 :(得分:0)

我建议使用webelement变量来存储结果然后定义返回它...对不起我不擅长Java。

有些事情是这样的。

//getElementByXPath function for static xpath
public WebElement getElementByXPath(String Key){
try{
    //This block will find element using Key value from web page and return It.
    WebElement  xpathElem = driver.findElement(By.xpath(Object.getProperty(Key)));
   if(xpathElem != null)
   {
    return xpathElem; 
    }
    else
    {
      Add_Log.debug("Object not found for key --"+Key);
      return null;
    } 
 }catch(Throwable t){
    //If element not found on page then It will return null.
    Add_Log.debug("Object not found for key --"+Key);
    return null;
 }
}

答案 1 :(得分:0)

当你使用try / catch时,遇到异常时它会被catch块处理。如果你想在log语句之后抛出同样的异常,那么你可以试试这个

 public WebElement getElementByXPath(String Key){
        try{
            //This block will find element using Key value from web page and return It.
            return driver.findElement(By.xpath(Object.getProperty(Key)));
        }catch(Throwable t){
            //If element not found on page then It will return null.
            Add_Log.debug("Object not found for key --"+Key);

            //error message is thrown as exception which will appear in testng reports generally if you are using
            throw new Exception(t.getMessage());
        }
    }