Reputation: 305
At the end of every test case I am checking to see if an error is present by calling the following code. The problem I have is even if an error is not present the code will throw a NoSuchElementException
and will fail the test case. If the error is present the test case will pass.
How can I modify my code so if an error is not present the test will pass and if an error is present the test case will fail.
public static void chk_ErrorIsNotEnabled()
{
try
{
element = driver.findElement(By.id("ctl00_Content_ulErrorList"));
if(element.getText().equals(""))
{
Log.info("Warning error is not dispayed." ); // The test should pass if element is not found
}
else
{
Log.error("Warning error is dispayed when it shouldnt be.");
} //The test should fail if element is found
}
catch (NoSuchElementException e){}
}
Upvotes: 1
Views: 1828
Reputation: 1
You could also create one method for navigation by ID which you will reuse every time and simple assertion should solve your problem
private WebElement currentElement;
public boolean navigateToElementById(String id) {
try {
currentElement = currentElement.findElement(By.id(id));
} catch (NoSuchElementException nsee) {
logger.warn("navigateToElementById : Element not found with id : "
+ id);
return false;
}
return true;
}
An then every time in you test you could use :
assertTrue(navigateToElementById("your id"));
Upvotes: 0
Reputation: 16201
The issue is the element is not present and selenium
throws NoSuchElement
exceptions which eventually catch the catch
block while your code expect an element with this id ctl00_Content_ulErrorList
. You cannot get text on an element which does not exist.
A good test will be something like the following:
Notice the findElements()
here. It should find the size
of the elements with error list. If that is more than 0
you know that errored out and test should fail
if(driver.findElements(By.id("ctl00_Content_ulErrorList")).size() > 0){
Log.error("Warning error is dispayed when it shouldnt be.");
}else{
//pass
Log.info("Warning error is not dispayed." ); // The test should pass if element is not found
}
Upvotes: 2