在SeleniumWebDriver中测试负流
问题:-webelement(按钮)isdisplayed()不适用于负面场景 要求:-如果屏幕上没有显示按钮,我需要使测试流程失败,如果按钮存在,则继续执行流程 代码:-在SeleniumWebDriver中测试负流,selenium,selenium-webdriver,Selenium,Selenium Webdriver,问题:-webelement(按钮)isdisplayed()不适用于负面场景 要求:-如果屏幕上没有显示按钮,我需要使测试流程失败,如果按钮存在,则继续执行流程 代码:- if (driver.findElement(By.id("button")).isDisplayed() == false) { System.out.println("The Button isn't present. Exiting!!"); driver.findElement(By.linkText("Logout
if (driver.findElement(By.id("button")).isDisplayed() == false) {
System.out.println("The Button isn't present. Exiting!!");
driver.findElement(By.linkText("Logout")).click();
}
else
{
//Proceed with the positive flow
}
在上面的代码中,如果按钮在屏幕上根本不存在,测试应该失败(if语句应该执行,但它不是)正如TestAutomationEngr所提到的,确保页面上只有一种类型的按钮 在webdriver中测试负流的另一种方法是使用try-and-catch 就你而言
boolean buttonFound=false;
try
{
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id("button")));
buttonFound=true;
}catch(Exception e)
{
System.out.println("The Button isn't present. Exiting!!");
driver.findElement(By.linkText("Logout")).click();
}
if(buttonFound)
{
//positive flow
}
这里我等10秒看元素的可见性
- 如果找到,
设置为true,因此执行正向流按钮found
- 如果未找到,将显示catch子句中的消息,并单击注销链接
WebElement elem = driver.findElement(By.id("button"));
Assert.assertTrue(elem.isEnabled());
最后,您只需要在测试中关闭驱动程序,然后拆下
driver.close()
您可以使用FindElements.Count方法 像这样:
public bool IsElementDisplayed(IWebDriver driver, By element)
{
if (driver.FindElements(element).Count > 0)
{
if (driver.FindElement(element).Displayed)
return true;
else
return false;
}
else
{
return false;
}
}
希望有帮助。你能发布按钮的html吗?另外,你确定页面上只有一个这样的按钮吗?是的,这个id只有一个按钮(听起来很奇怪,但在所有按钮中,有一个按钮的id为“button”)。上述方法的问题是在正向流的情况下,如果代码在任何时候中断,它将转到catch块并通过测试用例,即使测试用例失败。