我正在尝试填充一个动态,从中自动生成用户信息。所以我想为 from 的字段设置其他条件。所以我在步骤防御中使用 if else 循环,但假设如果条件为真,代码可以执行,但如果"如果条件失败,代码卡在 else 循环为什么。请帮忙
代码如下
@And("^Input Height in add report$")
public void Input_Height_in_add_report(DataTable newHeight) throws Throwable {
if(driver.findElement(By.xpath("//label//span[contains(text(),'Height')]")).isDisplayed()){
Thread.sleep(2000);
List<List<String>> data = newHeight.raw();
driver.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/form/div[7]/div[1]/div/div/input")).sendKeys(data.get(1).get(1));
}
else{
}
}
问题是,如果findElement
找到元素,它就会 if 语句,但如果它找不到元素,它会给出NosuchElementFound
异常。要处理这个问题,您可以使用try-catch块在else
中运行代码,请检查以下内容:
@And("^Input Height in add report$")
public void Input_Height_in_add_report(DataTable newHeight) throws Throwable {
try {
if(driver.findElement(By.xpath("//label//span[contains(text(),'Height')]")).isDisplayed()){
Thread.sleep(2000);
List<List<String>> data = newHeight.raw();
driver.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/form/div[7]/div[1]/div/div/input")).sendKeys(data.get(1).get(1));
}
}
catch(Exception e) {
// your else code should be here
}
}