任何人都可以帮我解决以下我希望在if / else条件下使用的场景。我正在使用带有Testng Eclipse的java。
1)如果登录成功并导航到主页,请避免尝试/捕获 2)如果登录失败,请转到尝试阻止。
driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.name("login")).submit();
try{
Assert.assertFalse(driver.findElement(By.xpath("//div[@class='errorMsg']")).getText().matches("Username or password incorrect. Try again."));
}
catch(Throwable t){
Assert.fail("Username Or Password is Incorrect.");
}
Assert.assertEquals(actualTitle, title,"Home is not accessible!");
答案 0 :(得分:0)
这就像用try-catch
替换if
一样简单,但如果没有找到任何元素,findBy
会抛出异常,那么至少有以下两种方法< / p>
1)创建一个可重用的findElementIfPresent
方法,如果没有找到任何元素,则返回null:
private WebElement findElementIfPresent(WebDriver driver, By by){
try {
return driver.findElement(by);
} catch (NoSuchElementException e) {
return null;
}
}
...
driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.name("login")).submit();
// obtain the div which holds the information
WebElement errorDiv = findElementIfPresent(driver, By.xpath("//div[@class='errorMsg']"));
// if the div exists and it has an authentication-problem messages, fail
if(errorDiv != null && errorDiv.getText().matches("Username or password incorrect. Try again."))
fail("Username Or Password is Incorrect.");
}
// otherwise proceed with additional verifications
assertEquals(actualTitle, title,"Home is not accessible!");
2)使用javadoc's suggestion并使用findElements(By)
返回元素列表。在您的特定情况下,如果列表为空,则验证成功,否则验证失败
// obtain the list of error divs
List<WebElement> errorDivs = driver.findElements(By.xpath("//div[@class='errorMsg']"));
// if there is at east one element present
if(!errorDivs.isEmpty()){
// pick first one and use as main failure reason
fail(errorDivs.get(0).getText());
}
// otherwise proceed with additional verifications
assertEquals(actualTitle, title,"Home is not accessible!");