It'd be as simple as replacing the try-catch
with an if
, but since findBy
will throw exception if no element is found, you have at least the following 2 approaches
1) create a reusable findElementIfPresent
method which returns null if no element is found:
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) go with the javadoc's suggestion and use findElements(By)
which returns a list of elements. In your particular case, if the list is empty then the authentication was successful, otherwise fail the test
// 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!");